Microsoft has recently released the Visual Studio 2013 Preview 1, which includes ASP .NET Web API 2. One of the most notable new additions to Web API is attribute-based routing. Prior to version 2, all routing in Web API was convention-based, as it is in ASP.NET MVC. Convention-based routing is great for most cases, but can be cumbersome if you need to specify many custom route templates.

You may want to use attributed routing if you need many custom routes in a controller, or just want to have a more SEO-friendly routes. Web API 2 includes a few different types of routing attributes. To start with, the base HttpGet, HttpPut, HttpPost, and HttpDelete now have an override that allows you to specify a custom route template. For example, if your Web service is for a blog, you could have a route for a particular entry in multiple formats, such as blog/2013-8-28/ or blog/8-28-2013/ to retrieve all entries for Aug. 28, 2013. You can also create more complex routes too; if you wanted to get all blog posts from a particular author for a given date, you could define a route like blog/evogel/2013-8-28/.

In addition to just overriding routes for a particular controller action, you can also set a custom route template for an entire controller by using the RoutePrefix attribute. The RoutePrefix attribute is best to use when you want all of your controller actions to have a particular custom path. For example, if you wanted all blog posts to be available at api/blogs, you’d use the following RoutePrefix attribute:

[RoutePrefix("api/blogs")]

You can also apply constraints and default values in a controller action route attribute. The built-in route template constraints include some value-type checks as well as range checks. For example, to specify that a route template parameter named orderId is an integer type, you’d use the following attribute:

[HttpGet("orderId:int")]

There’s also an included regex parameter constraint for high flexibility. In addition, you can create custom route template constraints by implementing the IInlineContraintResolver interface; but I’ll leave that for a future article.

#api #programming

Web API 2 Routing Attributes- Part 1
1.25 GEEK