Asp.Net Mvc Areas 的用法与好处
前言 在项目中为什么要使用Areas 进行分离
大家都知道,一般的Web应用都有前台(面向用户)和后台(面向管理员)两部分,我们希望以/localhost/Admin 开始的Url 是用户的后台管理地址,因此我们会这么配置自己的路由图。
routes.MapRoute(
name: "Admin",
url: "Admin/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
运行程序,我们会发现,localhost/Admin/AdminUser/Add 和 localhost/AdminUser/Add 都能打开Add 页面,这与我们的初衷相悖,我们要的是Url只有localhost/Admin/AdminUser/Add
能打开管理页面,怎么解决?
一:使用路由限制 Contraints 限制控制器为Admin
routes.MapRoute(
name: "Admin",
url: "Admin/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
constraints:new { controller=@"^Admin.*$" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
constraints:new { controller=@"^[^A].*$"}
);
运行代码,基本满足我们的需要,但是使用这种方法,感觉有点逊呀
二:让分离Area登场
在add 中选择区域

然后配置路由表,使用NameSpace 限制
参考别人的博客地址:http://blog.csdn.net/a497785609/article/details/50160605
浙公网安备 33010602011771号