Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Url from ApiController and Action names, in a project containing Controllers and ApiControllers

An existing project has controllers that inherit from either:

  • Controller: RouteTable.Routes.MapRoute with "{controller}/{action}/{id}".
  • ApiController: GlobalConfiguration.Configure and in the callback MapRoute with "api/{controller}/{id}".

Everything works fine, but I need to generate URLs for action methods in both of these types of controllers. Given:

  1. a name or type of a controller that inherits from either of these, and
  2. an action method name

Then from the web site side, how can I generate proper URLs for the web API side?

I'm using reflection to get action and controller names right now, and then through using UrlHelper.Action(actionName, controllerName, routeValueDictionary) am getting the correct URL for web site routes.

However, this method is (of course) generating URLs like this for the WebAPI side: /ApiControllerName/Get?parameter1=value when it needs to be /api/ApiControllerName?parameter1=value and the separate knowledge that it's a GET request.

Purpose: this is for a smoke test page for the web site that uses attributes and reflection to decide what to smoke test. It would be nice to be able to use the same attribute throughout the project, and furthermore it would be very nice to be able to use the correct UrlHelper that is aware of the routing tables and can produce the right prefix such as /api/, instead of the code assuming, perhaps wrongly, that the API routes were registered with api and not, say, webapi.

Update

After continued research I have found the Url.HttpRouteUrl method which can generate WebAPI URLs, but this requires knowing a route name, not an action method name.

I've done even more research on this and haven't gotten any closer to a solution. It looks like if you know the route name of the appropriate route, you can cook up a Url easily. There are also some likely hints here and here. But if there are multiple routes for WebApi, how do you know which one matches the controller and action you want? It would be dumb to reimplement what MVC itself already does in selecting a controller and action. I guess I could construct a URL from the given parameters using every WebApi route, then run the URL through its paces (using some of the above links) and see if it is going to match the desired controller... yuck.

There's got to be an easier way.

For now I'm going to have to move on, but here's to hoping someone can help me out.

like image 842
ErikE Avatar asked Mar 10 '16 00:03

ErikE


1 Answers

Here a few ways of do it:

  • Using RouteUrl() method:

    var url1 = Url.RouteUrl(new { id = 1, controller = "...",  httproute = true });
    

The trick is of course httproute = true. Setting this property, you inform that you only want http routes (Web Api routes).

  • Using HttpRouteUrl() method:

    var url2 = Url.HttpRouteUrl(null, new { id = 2, controller = ".." });
    
  • And another way to do it using directly the routes and httproute value:

    var values = new RouteValueDictionary(new
    {
        id = 3,
        controller = "...",
        httproute = true
    });
    var url3 = RouteTable.Routes.GetVirtualPath(Request.RequestContext, values).VirtualPath;
    

The 3 ways are basically the same. Since you don't specify the route, the system will try to find the first match according to the route values. For example, lets say you have an ApiController called RestfulController and web api routes are configured like so:

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

Using the first method, when you do var url = Url.RouteUrl(new { id = 123, controller = "restful", httproute = true }); in a MVC Controller, the value in url is /api/restful/123.

But if you add a new route ConstraintApi:

config.Routes.MapHttpRoute(
    name: "ConstraintApi",
    routeTemplate: "api2/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional },
    constraints: new { controller = "restful" }
);

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

The url returned by RouteUrl is /api2/restful/123.

You should be aware the order when you are declaring your routes. If the route DefaultApi is added before the route ConstraintApi, the url generated is /api/restful/123.

like image 152
Arturo Menchaca Avatar answered Sep 18 '22 17:09

Arturo Menchaca