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:
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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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