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

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.

主站蜘蛛池模板: 天祝| 玉田县| 嘉黎县| 元阳县| 汽车| 临漳县| 新巴尔虎左旗| 柳江县| 通江县| 临猗县| 鸡西市| 盖州市| 阿拉尔市| 车险| 秭归县| 呼和浩特市| 定远县| 芮城县| 汝城县| 绍兴市| 岢岚县| 嵩明县| 洛宁县| 汉阴县| 平塘县| 平潭县| 青海省| 明溪县| 酉阳| 清流县| 淅川县| 伊宁市| 长岭县| 抚州市| 安乡县| 延长县| 板桥市| 额尔古纳市| 林州市| 盐亭县| 防城港市|