我的ASP.NET MVC3应用程序中有一些区域: namespace MyProject.Areas.myarea{ public class myareaAreaRegistration : AreaRegistration { public override string AreaName { get { return "myarea"; } } public override void RegisterArea(Ar
namespace MyProject.Areas.myarea
{
public class myareaAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "myarea";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"myarea_default",
"myarea/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
}
}
这个区域包含“Hello”控制器,带有“Smile”动作.
在整个项目的global.asax文件中,我有:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
所以,当我请求“localhost / myarea / hello / smile”时,它按预期调用适当的控制器.
但!当我请求“localhost / hello / smile”时,它会调用hello控制器STILL!有了它,它会查找不在myarea / Views文件夹中的视图,而是在〜/ Views文件夹中查找项目的“root”(非区域)级别.
我该如何修复此问题,因此服务器将抛出404异常,找不到该资源,就像我请求不存在的控制器一样?
UPD:区域中的控制器位于命名空间中:
namespace MyProject.Areas.myarea.Controllers
{
public class HelloController : Controller
...
}
“root”-level中的控制器位于命名空间中:
namespace MyProject.Controllers
{
public class AnotherRootController : Controller
...
}
所以我在global.asax中试过这个:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new [] { "MyProject.Controllers" } //Namespace
);
}
我认为这会将此路由限制为“root”级控制器,因为它们位于MyProject.Controllers命名空间中.那不行.区域控制器仍在使用请求进行调用,但不包含其中的任何名称.
可能有人可以解释,为什么?
在Global.asax中注册默认路由时,可以通过将其限制为仅查找给定命名空间中的控制器来设置UseNamespaceFallback = false数据语句.你可以看看 following blog post.因此,要将其付诸实践,请为您的区域注册添加命名空间限制:
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"myarea_default",
"myarea/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional },
new[] { "MyProject.Areas.myarea.Controllers" }
);
}
并且在注册默认路由时,在Global.asax中将UseNamespaceFallback数据标记设置为false,以便将其约束到给定的命名空间:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { "MyProject.Controllers" }
).DataTokens["UseNamespaceFallback"] = false;
}
