简体   繁体   中英

Access Web API routing from ASP.NET MVC application

I have a solution with 2 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 2 projects were one I could generate a link for my api like this:

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

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

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

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

Or you could do this to specify it a webapi route.

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

But you do need the WebApi registration done in your Global.asax and have the NuGet WebApi package installed.

Also, typically actions aren't included in the route as you've referenced above in your links. They're typically unnamed and provided by request (GET, POST PUT, ect). Those are omitted unless your route config looks something like this.

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

I had a similar issue once.

My solution was creating interfaces for each one of the WebApi controllers that could be shared among your projects (MVC and WebApi). To each one of the WebApi controllers add an action (I will refer to it as 'Routes' action) that returns serialized Collection of key-value elements, where keys are interface (WebApi) method names and values are objects that contain routes and http methods (Get,Post etc) (It is constructed in WebApi project so you have access to it's routing table).On MVC application start you can issue a request to your WebApi Routes action and get all it's routes. Then you can store it in a global readonly dictionary for a quick access. Getting a particular route becomes a trivial task because your interface method names are keys to the dictionary you filled earlier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM