ASP.NET Core MVC中Area的使用
首先,在Solution Explorer下新建一个Areas文件夹。
然后右击该文件夹,选择“Add” -> “Area”,新建Area。如下所示:
然后分别设置其相应的Controller和View。
AnotherController.cs
[Area("AnotherArea")] public class AnotherController : Controller { public IActionResult Index() { return View(); } }
Index.cshtml
@{ ViewData["Title"] = "Another Page"; } <div class="text-center"> <h1 class="display-4">Another Index</h1> </div>
在这里新建一个Controller(ShowMessageController),然后将默认的路由导向该Controller。
ShowMessageController.cs
public class ShowMessageController : Controller { public IActionResult Index() { return View(); } }
Index.cshtml
@{ Layout = null; } <div class="text-center"> <h1 class="display-4">ShowMessage Index</h1> <ul> <li><a class="dropdown-item" asp-area="MyAreaTest" asp-controller="ShowTest" asp-action="Index">Show Test</a></li> <li><a class="dropdown-item" asp-area="AnotherArea" asp-controller="Another" asp-action="Index">Another</a></li> <li><a class="dropdown-item" asp-area="MyThirdArea" asp-controller="Third" asp-action="Index">Third</a></li> </ul> </div>
再在Startup.cs中设置路由。
public class Startup { // ... // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // ... app.UseEndpoints(endpoints => { endpoints.MapAreaControllerRoute( name: "MyAreaTest", areaName: "MyAreaTest", pattern: "MyAreaTest/{controller=ShowTest}/{action=Index}/{id?}"); endpoints.MapAreaControllerRoute( name: "AnotherArea", areaName: "AnotherArea", pattern: "AnotherArea/{controller=Another}/{action=Index}/{id?}"); endpoints.MapAreaControllerRoute( name: "MyThirdArea", areaName: "MyThirdArea", pattern: "MyThirdArea/{controller=Third}/{action=Index}/{id?}"); endpoints.MapControllerRoute( name: "default", pattern: "{controller=ShowMessage}/{action=Index}/{id?}"); }); } }
把圈子变小,把语言变干净,把成绩往上提,把故事往心里收,现在想要的以后你都会有。