Thursday, October 6, 2016

Creating Route Constraints using Attribute-based Routing in ASP.NET Web API

When you are writing your Web API methods, you may encounter a situation whereby you have two different methods that need to be distinguished from each other through their routes?

For example, if you have a method GetById(int id) and GetById(string id), how do you distinguish between these 2 routes when documenting your Web API using Attribute-based routing?

Well, through Route Constraints of course!

https://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2#constraints

Therefore, you can then have Web API methods like the following:


[Route("{id:int}")]
[HttpGet]
public IHttpActionResult GetById(int id)
{
try
{
return Ok(_myRepository.GetById(id));
}
catch (Exception ex)
{
return BadRequest(ex.UnwrapInnerExceptionMessages());
}
}
[Route("{id}")]
[HttpGet]
public IHttpActionResult GetById(string id)
{
try
{
return Ok(_myRepository.GetById(id));
}
catch (Exception ex)
{
return BadRequest(ex.UnwrapInnerExceptionMessages());
}
}

No comments:

Post a Comment