Reputation: 65266
I have a web api end point with a route parameter. It works with or without the route parameter type. I just would like to know why specify this in the following code?
[HttpGet]
[Route("{myId:int}")]
public HttpResponseMessage GetData([FromUri] int myId)
{
//code here
}
This snippet [Route("{myId:int}")]
. Why specify the int? There is already a int in this [FromUri] int myId
. Wouldn't int for the route be redundant? Is there any reason for this?
Upvotes: 16
Views: 6203
Reputation: 44600
Please see this example:
[Route("users/{id:int}"]
public User GetUserById(int id) { ... }
[Route("users/{name}"]
public User GetUserByName(string name) { ... }
Here, the first route will only be selected if the "id" segment of the URI is an integer. Otherwise, the second route will be chosen.
So in your case it's not required. But would be necessary if you need smarter route resolution. There are many different constraints that you can use. For example {x:minlength(10)}
- string with min length of 10. {x:max(10)}
- Matches an integer with a maximum value of 10. {x:regex(^\d{3}-\d{3}-\d{4}$)}
- regex constraints etc.
You can find all the available constraints in the documentation.
Upvotes: 36