在全局配置文件(Global.asax.cs)中配置区域路由规则,指定控制器和动作的命名空间,以及区域名称。例如:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteTable.Routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "MyProject.Controllers" }
);
}
}
在上述代码中,namespaces
参数指定了控制器和动作的命名空间。如果要在区域中查找控制器,需要指定区域的命名空间,例如:
public class BlogAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Blog";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Blog_default",
"Blog/{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { "MyProject.Areas.Blog.Controllers"}
);
}
}
在上述代码中,new[] { "MyProject.Areas.Blog.Controllers" }
参数指定了在区域Blog
中查找控制器的命名空间。
这样配置后,MVC框架会在全局和区域中查找控制器,而不仅仅是在根目录中查找。