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

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.

主站蜘蛛池模板: 山丹县| 安宁市| 商水县| 夏邑县| 无为县| 张家口市| 咸宁市| 喀喇沁旗| 延庆县| 民丰县| 虞城县| 安泽县| 平乡县| 星座| 永顺县| 文安县| 嘉定区| 曲靖市| 博野县| 龙海市| 商洛市| 宁武县| 西平县| 高台县| 东乌珠穆沁旗| 北川| 长沙县| 定远县| 岳阳县| 卢龙县| 南康市| 诸暨市| 呼伦贝尔市| 博白县| 离岛区| 内丘县| 普兰县| 连云港市| 金华市| 堆龙德庆县| 定陶县|