Get Current Route Name From ASP.NET Web API Request

At RIMdev, we are attempting to layer Hypermedia concepts into our APIs. One of these concepts is to have a collection of links to related resources on our responses. While on face value it may seem simple to generate links, it can be daunting given the many options you have to do so. We have decided to leverage the current Web API infrastructure and UrlHelper to more consistently generate links and adapt to our architectural changes. We even wrote a NuGet package called SupUrlative that makes it really easy to do so.

Note that SupUrlative needs a routename. In most instances, the route name is obvious. In some instances of code reuse, you’ll need to dynamically understand where you are in the code and ask the question.

We have already decorated our action with the route name. Using that string again is redundant and prone to errors. There is a better approach.

[HttpGet, HttpPost][Route("", Name = "SearchIndex")]publicasyncTask<IHttpActionResult>Index(SearchIndexRequestrequest){vargenerator=newGenerator(httpRequestMessage);// Our extension method to get the current route name: "SearchIndex"varrouteName=url.GetCurrentRouteName();varresult=generator.Generate(routeName,request);}