ASP. NET MVC 6 attribute routing–the [controller] and [action] tokens

Source: Internet
Author: User

Original: http://www.strathweb.com/2015/01/asp-net-mvc-6-attribute-routing-controller-action-tokens/

When you use Routing properties in Web API 2 or MVC 5, it is very easy to take a situation where the routing and controller names are not synchronized. This is because the route is usually a string, so when we change the name of the controller we also have to modify the routing properties.

We usually forget to change it at that time.

This problem has been improved in MVC 6 – by introducing [controller] and [action] tokens to the route properties.

Problem

The controller code for a typical Web API project is as follows:

[Route ("Api/hello")]public class hellocontroller:controller{    [route] public    string Get ()    {        return "Hello";    }}

Or:

[Route ("Api/hello")]public class hellocontroller:controller{    [Route ("Gethello")]    public string Gethello ()    {        return "Hello";    }}

In the two examples above, we usually need to manually maintain the route properties.

MVC6 Solutions

By using the new [controller] token you can ensure that your routing and controller names remain the same. In the example below, [controller] is always the same as the name of the controller – in this case the name of the route is Hello.

[Route ("api/[controller]")]public class hellocontroller:controller{    [route] public    string Get ()    {        return "Hello";    }}

[Action] token– This app keeps the name of the route and action consistent on the Aciton.

In the following example, the action matches the /API/HELLO/GETHELLO/1 URL.

[Route ("Api/[controller]")]public class hellocontroller:controller{    [Route ("[Action]/{id:int}")]    public string Gethello (int id)    {        return "Hello" + id;    }}

ASP. NET MVC 6 attribute routing–the [controller] and [action] tokens

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.