1 Comments

With the introduction of ASP.NET WebAPI 2 came two new attributes, Route and RoutePrefix. By default route resolving is done using the controller name and then appending controller, from there the framework will try and find a matching controller class and load it up and execute the given action or HTTP VERB. So given this ValuesController class (ValuesController is part of the default WebAPI template when starting a new project, as well as a whole lot of scripts and css…… but that’s another debate).

public class ValuesController : ApiController
{
    // GET api/values
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/values/5
    public string Get(int id)
    {
        return "value " + 5;
    }
}

when requesting this route:

GET http://localhost:64770/api/values/5

We know that we will get back a response(XML, JSON, or any other format you want to support) with the HTTP Status code of 200 (OK) with the string values 5 in the response body.

Now if I were to add the Route attribute on the GET action:

[Route("api/foo/{id}", Name = "GetFoo")]
public string Get(int id)
{
    return "value " + id;
}

and requesting the previous URL we will now have a 404 (Not Found) response and a message stating that “No HTTP resource was found that matches the request URI”, but by calling

GET http://localhost:64770/api/foo/5

 

We now get a 200 (OK) response with the string values 5 in the response body, just like before. The {id} is used for parameter binding and eventually can be used for route constraints. When adding the route attribute, you can choose to give it a name and an order. If you need (most probably) to add route constraints to your route it can be done by following the route constraints semantic (another blog post).

Don’t forget that for you routes to be properly mapped, you must make sure that in the WebApiConfig.Register method that this line of code:

config.MapHttpAttributeRoutes();

is present otherwise you will get HTTP 404.

So with this attribute we can now easily define a bunch of routes inside a controller, even go for versioning, wihtout having to override classes.

Next up route constraints!

Comments

Comment by Just Code It

WebAPI Route attribute and constraints

WebAPI Route attribute and constraints