Saturday, November 15, 2014

Specify route order in Web API 2.0

Web API 2.0 provides attribute routing, which allows us to specify routing template for each action. Now, the question is if we specify same routing template in two different actions when which one will execute at first?

In case of tie, routes are ordered by a case-insensitive order string comparison (OrdinalIgnoreCase) of the route template.


If we want to specify sequence of execution then we can specify it by setting value in Order property.  Have a look on below example.

public class BlogController : ApiController
    {
        [Route("blog/getBlog/{id}", Order = 0) ]
        public void Get(Int32 Id)
        {
        }

        [Route("blog/getBlog/{id}", Order = 1)]
        public void GetById(Int32 Id)
        {
        }
    }


We have defined Get() and GetById() actions in Blog controller. Just have a look on Route template above actions. Both are defined same. But the first Action (Get) enjoying the lower Order means if request comes for this route pattern then Get() will execute at first .

Let us look in action. I am using fiddler to generate HTTP payload. This is the url which matches with same pattern.



We are seeing that the Get() has executed because it’s enjoying lower Order. Let’s change the order now.
If we execute same url then we will see that GetById() has executed now because now it’s enjoying lower Order value


Order property is really helpful if there are same routing template in both actions. 


No comments:

Post a Comment