When I create a new ASP.NET MVC project one of the first things on my to do list is to implement attribute routing. It’s a much cleaner (and obvious) way to handle your POST and GET functions for your web service.

Have a look at the code below:

  <Route("api/GetDailyStats/{UserID}/">
  <HttpGet>
  Public Function GetDailyStats(ByVal UserID As Long) As List(Of DailyStat)
  End Function

I can see exactly what URI path I need to call for this function, what parameters it is expecting and that this is a HTTP Get function.

Setting this up is really easy. Just follow these steps:

  1. Using the NuGet package manager make sure you have installed Microsoft.AspNet.WebApi.WebHost
  2. In the App_Start folder of your ASP.NET project, edit the WebApiConfig.vb file and add the following line before any other config calls
    
    config.MapHttpAttributeRoutes()
    
  3. That’s it! Now you can add the Route Attribute and HTTP method to the top of your controllers functions and subs

Some extra information in case you need it

HTTP Methods

You don’t have to specify the HTTP Method but you do need to be strict with your function naming convention.
If the HTTP method is not specified the Web API will determine the method by looking at the start of the function/sub name.
In my example above I don’t really need to specify that the HTTP method is HttpGet because my function is called GetDailyStats.
(The match is case-insensitive.)

Route Prefix

If all of the routes in your controller start with the same prefix e.g. api/ you can save yourself some typing by using the RoutePrefix attribute.

For example, have a look at this code:

 Public Class DataController
        Inherits ApiController

 <Route("api/GetDailyStats/{UserID}/">
  <HttpGet>
  Public Function GetDailyStats(ByVal UserID As Long) As List(Of DailyStat)
  End Function

 <Route("api/PutDailyStats/{UserID}/">
  <HttpPut>
  Public Function PutDailyStats(ByVal NewStat As DailyStat) As Boolean
  End Function

 End Class

We can rewrite it by adding the RoutePrefix attribute to the class definition

' add route prefix at the class definition
<RoutePrefix("api")>
 Public Class DataController
        Inherits ApiController

' remember to remove your prefix from your routes
 <Route("GetDailyStats/{UserID}/">
  <HttpGet>
  Public Function GetDailyStats(ByVal UserID As Long) As List(Of DailyStat)
  End Function

 <Route("PutDailyStats/{UserID}/">
  <HttpPut>
  Public Function PutDailyStats(ByVal NewStat As DailyStat) As Boolean
  End Function

 End Class