Thursday, March 24, 2016

Understanding Routing in ASP.NET Web API

If you are interested in learning more about Routing in ASP.NET Web API, then you should definitely check out these articles:

http://www.asp.net/web-api/overview/web-api-routing-and-actions

However, one thing I discovered as part of my development which is not obviously covered in these articles are the nuances of routing in ASP.NET Web API.

For example, if you have this type of a method signature defined in Web API:


public IEnumerable<Order> Get(int id)

You will then need to define a route similar to this:


[Route("{id}")]

However, if you instead define a method signature like the following:


public IEnumerable<Order> Get(int orderId)

Your existing route WILL NOT WORK!

Instead, you will have to define your route like this:


 [Route("{orderId}")]

Alternatively, you can do something like the following as well to match them up:


public IEnumerable<Order> Get(int [FromUri(Name = "id")] orderId)

This subtle nuance is not well documented in Microsoft's MSDN documentation nor on the ASP.NET website, but it is useful to know!!

No comments:

Post a Comment