Accessing the web API from an ASP.NET MVC application

I have a solution with two projects. One is an ASP.NET Web API project and the other is an ASP.NET MVC project. The web api will be consumed from various clients. If the two projects were one, I could create a link for my api like this:

@Url.RouteUrl("ActionApi", new { httpRoute = string.Empty, controller = "User", action = "AddChildAsync" });  

      

But now that the two projects are separated, I cannot do this because the mvc app cannot find the configuration for the web api (although I have a project link from the mvc app to the web api). So, is there an elegant way to access web api configuration and dynamically generate links? Thanks in advance.

+3


source to share


2 answers


You should be able to access it by changing httproute = true.

@Url.RouteUrl("ActionApi", new { httpRoute = true, controller = "User", action = "AddChildAsync" });

      

Or you can do this to specify the webapi route.

@Url.HttpRouteUrl("ActionApi", new { controller = "User", action = "AddChildAsync" });  

      



But you need the WebApi registration done in your Global.asax and install the WebApi NuGet package.

Also, usually actions are not included in the route, as you stated above in your links. They are usually unnamed and provided upon request (GET, POST PUT, etc.). They are omitted unless your route configuration looks something like this.

routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional } );

      

+2


source


I had a similar problem.



My solution was to create interfaces for each of the WebApi controllers that could be shared with your projects (MVC and WebApi). To each of the WebApi controllers, an action is added (I'll refer to it as the Routes action) that returns a serialized collection of key value items, where the key names are interfaces (WebApi) and the values ​​are objects that contain routes and http methods (Get, Post, etc.) (it is constructed in the WebApi project, so you have access to the routing table). At the start of the MVC application, you can send a request for the "WebApi Routes" action and get all its routes. Then you can save it to the global readable dictionary for quick access. Getting a certain route becomes a trivial task,because your interface method names are keys to the vocabulary you filled out earlier.

+1


source







All Articles