Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why specify route parameter type in web api?

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?

like image 919
Luke101 Avatar asked Jul 12 '16 16:07

Luke101


People also ask

How do I use the route attribute with web API?

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.

What is routing in web API 2?

"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.

How does web API route HTTP requests to controllers?

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.

What is the reason to use API in route template?

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.


1 Answers

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.

like image 113
Andrei Avatar answered Sep 21 '22 12:09

Andrei