官术网_书友最值得收藏!

Adding routes via route attributes

Adding routes via route attributes is a way of defining the route for every controller action as an attribute on top of controller action methods.

Within the controller class (in our case, HomeController), add the Route attribute before the Index method:

[Route("Home/Index")]
public IActionResult Index()
{
return View();
}

This instructs ASP.NET Core MVC to pass requests to the Index method whenever the URL looks like http://example.com/Home/Index. As patterns are not supported in attribute routing, if we want to make the Index method of HomeController the default of the application, then we need to add multiple Route attribute calls on top of the Index method:

[Route("")]
[Route("Home")]
[Route("Home/Index")]
public IActionResult Index()
{
return View();
}

Attribute routing makes it easier to add new routes and keep them up-to-date with name changes or architectural code changes, but it doesn't support complicated patterns and makes it harder to see the full route list of the application. Attribute routing is, in most cases, the preferred way for ASP.NET Core web APIs.

主站蜘蛛池模板: 三门峡市| 嘉义县| 洮南市| 洮南市| 襄城县| 昌吉市| 鄂州市| 天峻县| 辽中县| 胶南市| 太白县| 隆尧县| 广饶县| 遂宁市| 广元市| 溆浦县| 平顶山市| 余干县| 霍州市| 长宁区| 昌黎县| 中西区| 宜君县| 彭山县| 台前县| 原平市| 泾阳县| 白水县| 恩平市| 呼伦贝尔市| 余庆县| 嵊泗县| 青神县| 磴口县| 南康市| 和政县| 峡江县| 靖西县| 永清县| 鹿邑县| 陕西省|