[MVC 5] 快速加入Attribute Routing with Area
導覽
1. Application_Start 引入路由表
2. RouteConfig 設定
3. 建立區域
4. 於Areas/my/Controller/HomeController加入Attribute Routing
1. Application_Start 引入路由表
void Application_Start(object sender, EventArgs e)
{
// 應用程式啟動時執行的程式碼
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
2. RouteConfig 設定
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
AreaRegistration.RegisterAllAreas();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new string[] { "MyMvcWeb.Controllers" }
);
}
3. 建立區域
MyMVCWeb > 右鍵 > 加入 > 區域 , 輸入區域名稱 , 按[加入]
4. 於Areas/my/Controller/HomeController加入Attribute Routing
[Route("{action}")]
public class HomeController : Controller
{
//
[Route("")]
[Route("Home")]
[Route("Index")]
[Authorize]
public ActionResult Index()
{
return View();
}
}