Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get matched route name in Web API

In my Web API handler I need to get the name of the route that matched the request.

public class CurrentRequestMessageHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var route = request.GetRouteData().Route;
        //now what?

        return base.SendAsync(request, cancellationToken);
    }
}
like image 724
Ventsyslav Raikov Avatar asked Nov 08 '13 08:11

Ventsyslav Raikov


People also ask

Where is the route is defined in Web API?

This route is defined in the WebApiConfig. cs file, which is placed in the App_Start directory: For more information about the WebApiConfig class, see Configuring ASP.NET Web API.

What is difference between route and Routeprefix?

Route prefixes are associated with routes by design in attribute routing. It is used to set a common prefix for an entire controller.

What is action name in Web API?

ActionName attribute is an action selector which is used for a different name of the action method. We use ActionName attribute when we want that action method to be called with a different name instead of the actual name of the method.

What is the difference between Web API routing and MVC routing?

Route Processing In MVC, by default HTTP verb is GET for using others HTTP verbs you need defined as an attribute but in Web API you need to define as an method's name prefix.


1 Answers

Currently there is no way to retrieve the route name of a route in Web API. You can take a look at the HttpRouteCollection source code here for more details. If route name is definitely required for your scenario, you could stick in the route name in the data tokens of a route. (note that currently attribute routing doesn't provide a way to access the data tokens)

Update - 6/23/2014
With latest improvements(5.2 RC) in the area of attribute routing, you can do something like following to insert route names into data tokens.

config.MapHttpAttributeRoutes(new CustomDefaultDirectRouteProvider());

public class CustomDefaultDirectRouteProvider : DefaultDirectRouteProvider
{
    public override IReadOnlyList<RouteEntry> GetDirectRoutes(HttpControllerDescriptor controllerDescriptor, 
        IReadOnlyList<HttpActionDescriptor> actionDescriptors, IInlineConstraintResolver constraintResolver)
    {
        IReadOnlyList<RouteEntry> coll = base.GetDirectRoutes(controllerDescriptor, actionDescriptors, constraintResolver);

        foreach(RouteEntry routeEntry in coll)
        {
            if (!string.IsNullOrEmpty(routeEntry.Name))
            {
                routeEntry.Route.DataTokens["Route_Name"] = routeEntry.Name;

            }
        }

        return coll;
    }
}

Access it like this:
reequest.GetRouteData().Route.DataTokens["Route_Name"]

like image 179
Kiran Avatar answered Sep 24 '22 14:09

Kiran