ASP.NET MVC Attribute Routing


  1. 說明
    1. 使用範例
  2. 參考資料
  3. 相關連結

筆記 ASP.NET MVC 如何使用 Attribute Routing 的方式設定網址路由。

logo

說明

App_Start/RouteConfig.cs

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    // Enable Attribute Routing
    routes.MapMvcAttributeRoutes();

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

為了使用 Attribute Routing,首先需要在 RouteConfig.cs 當中以 MapMvcAttributeRoutes 進行啟用。

使用範例

public class HomeController : Controller
{
    [Route("About")]
    public ActionResult About()
    {
        return View();
    }
}

加入 RouteAttribute 後,原本需要使用 /Home/About 存取的 URL 路徑,只需要使用 /About 即可,相對地使用 /Home/About 則會發生 ASP.NET Http NotFound 的錯誤。

而如果仍要保持 /Home/About,可以透過多個 RouteAttrbibute 的方式達成。

public class HomeController : Controller
{
    [Route("About")]
    [Route("Home/About")]
    [Route("Information")]
    public ActionResult About()
    {
        return View();
    }
}

透過以上設定,以下三個網址都可以存取到 Home/About

/Home/About
/About
/Information

Route Variation

[Route("~/")]
[Route]

RoutePrefix & Default Action

Route Constraints

參考資料

ASP.NET MVC - 使用 Attribute Routing | mrkt 的程式學習筆記

相關連結

ASP.NET MVC 從無到有打造一個應用系統

Visual Studio 入門教學