WebApi Mvc Routing

0

Category :

Routing

Is how Web API matches a URI to an action. Web API 2 introduces attribute routing, which uses attributes to define routes, giving you more control over the URIs in your web API. convention-based routing you can combine both techniques in the same project.

HTTP Methods

Web API also selects actions based on the HTTP method of the request (GET, POST, etc). By default, Web API looks for a case-insensitive match with the start of the controller method name. For example, a controller method named PutCustomers matches an HTTP PUT request.

You can override this convention by decorating the mathod with any the following attributes
[HttpDelete] [HttpGet] [HttpHead] [HttpOptions] [HttpPatch] [HttpPost] [HttpPut]

Route Prefixes

You can set a common prefix for an entire controller by using the [RoutePrefix] attribute:

[RoutePrefix("api/books")]
public class BooksController : ApiController
{
    // GET api/books
    [Route("")]
    public IEnumerable Get() { ... }

    // GET api/books/5
    [Route("{id:int}")]
    public Book Get(int id) { ... }

    // POST api/books
    [Route("")]
    public HttpResponseMessage Post(Book book) { ... }
}
Use a tilde (~) on the method attribute to override the route prefix.
[Route("~/api/authors/{authorId:int}/books")]

Route Constraints

Route constraints let you restrict how the parameters in the route template are matched. The general syntax is "{parameter:constraint}"

[Route("users/{id:int}"]
public User GetUserById(int id) { ... }

Optional URI Parameters and Default Values

You can make a URI parameter optional by adding a question mark to the route parameter. If a route parameter is optional, you must define a default value for the method parameter or in the template.

[Route("api/books/locale/{lcid:int?}")]
public IEnumerable GetBooksByLocale(int lcid = 1033) { ... }

[Route("api/books/locale/{lcid:int=1033}")]
public IEnumerable GetBooksByLocale(int lcid) { ... }

Route Names

every route has a name. Route names are useful for generating links, so that you can include a link in an HTTP response. To specify the route name, set the Name property on the attribute.

[Route("api/books/{id}", Name="GetBookById")]
public BookDto GetBook(int id) 
{
 // Implementation not shown...
}

// Generate a link to the new book and set the Location header in the response.
string uri = Url.Link("GetBookById", new { id = book.BookId });

Route Order

When the framework tries to match a URI with a route, it evaluates the routes in a particular order. To specify the order, set the RouteOrder property on the route attribute. Lower values are evaluated first. The default order value is zero.
The order can be found on the reference page.

my thanks to:
https://docs.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2

0 comments:

Post a Comment