c# - How to call WebAPI from a MVC Controller in a different project? -


i have create web api existing mvc project , make api controllers calling service layer , models, contained in separate projects in same solution, create , map dtos.

layout of projects solution in vs ( ignore bookservice.cs. trying webapi tutorial , put in same solution temporarily).

i have been reading on webapi , how functions past 2 days, not being able grasp understanding on how create api controllers mvc project without referencing it? have make views @ end, in main project calling uri, confused @ point.

it me out lot if can please clarify how tackle or point me tutorial or sort of source learn process of working web api. thank you.

the web api project separate "website", need host individually. mvc project make requests web api using httpclient.

since web api separate, won't able utilize helpers url.routeurl, etc. urls web api actions. need know full uri web api, including it's domain. there no way programmatically ascertain information, recommend making use of application settings avoid hardcoding in mvc project.

right-click on mvc project in solution explorer , choose properties. click on settings tab. here, can add strongly-typed settings mvc application can utilize. importantly, these settings still persisted in web.config, can change them using config transforms. web api have different urls depending on whether you're in development vs. production, example, make easy ensure you're hitting right thing in right environment.

you can add setting webapiuri, , give type of system.uri. then, set string value of web api hosted in development, i.e. http://localhost:12345. it's important setting specific development environment, config transforms not applied in development. staging, production, etc. you'll change setting appropriately in applicable config transform, , updated right value right environment when publish.

then, when need work it, you'll like:

var client = new httpclient(); client.baseaddress = properties.settings.default.webapiuri; 

then, make requests normal through client. more information on working httpclient, see the documentation.


Comments

Popular posts from this blog

javascript - Clear button on addentry page doesn't work -

c# - Selenium Authentication Popup preventing driver close or quit -

tensorflow when input_data MNIST_data , zlib.error: Error -3 while decompressing: invalid block type -