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?
The Route attribute can be applied on any controller or action method. In order to use attribute routing with Web API, it must be enabled in WebApiConfig by calling config.MapHttpAttributeRoutes () method. Consider the following example of attribute routing.
"Routing is how Web API matches a URI to an action. Web API 2 supports a new type of routing, called attribute routing. As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web API.
by Mike Wasson. This article describes how ASP.NET Web API routes HTTP requests to controllers. Note. If you are familiar with ASP.NET MVC, Web API routing is very similar to MVC routing. The main difference is that Web API uses the HTTP verb, not the URI path, to select the action.
Note: The reason to use api in the route template is just to avoid confusion between MVC controller and Web API controller. You can use any pattern based on your app architecture. Visit asp.net to learn about routing in detail.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With