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);
}
}
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.
Route prefixes are associated with routes by design in attribute routing. It is used to set a common prefix for an entire controller.
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.
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.
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With