您的位置:首页 > 编程语言 > ASP

在Asp.Net Core中添加区域的简单实现

2016-11-02 18:08 741 查看
使用区域,可以有效的对业务进行隔离,各种业务及分工可以更灵活。在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几乎一样。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐