標籤:繼承 asp code apr 簡單實現 ccf model efault new
使用地區,可以有效對業務進行隔離,各種業務及分工可以更靈活。在Asp.Net Core中啟用地區也是極簡單的。
使用步驟:
1、在 Startup.cs 中添加地區的路由:
app.UseMvc(routes => { routes.MapRoute( name: "area", template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"); routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); });
2、在項目下面建立 Areas 檔案夾,並添加相應的 Controllers, Views, Models 檔案夾:
3、在 Controllers 下添加 HomeController.cs ,(通常我會建議,添加實際的 Controller 之前,先建立 BaseController ,並且其它所有Controller全部繼承自 BaseController,這樣在實際開發過程中,很多配置及常用方法可以更容易使用),並在Controller上應用屬性 [Area("名稱")],若在 BaseController 中進行設定。則繼承自 BaseController 的所有 Controller 都無需重複設定:
[Area("Mobile")] public class BaseController : Controller { // GET: /<controller>/ public IActionResult Index() { return View(); } }
4、後端重新導向的時候,需要加上Area屬性:
public IActionResult Test() { return RedirectToAction("index", "home", new { Area = "mobile" }); }
5、前端連結產生也需要加上 Area 屬性:
@{ ViewData["Title"] = "About";}<h2>@ViewData["Title"].</h2><h3>@ViewData["Message"]</h3><p>Use this area to provide additional information.</p><a asp-area="mobile" asp-controller="home" asp-action="index">Test</a>
OK,其它一些使用時注意事項,同以前的Asp.Net幾乎一樣。
在Asp.Net Core中添加地區的簡單實現