2013-0120

MVC 使用Areas后存在相同Controller时报错

作者: momy 分类: 编程开发 1 Comment »
摘要:Multiple types were found that match the controller named 'Home'. This can happen if the route that services this request ('{controller}/{action}/{id}') does not specify namespaces to search

报错如下:

Multiple types were found that match the controller named 'Home'. This can happen if the route that services this request ('{controller}/{action}/{id}') does not specify namespaces to search for a controller that matches the request. If this is the case, register this route by calling an overload of the 'MapRoute' method that takes a 'namespaces' parameter.

The request for 'Home' has found the following matching controllers:
MVC.Controllers.HomeController
MVC .Areas.Search.Controllers.HomeController

问题原因:使用Areas后存在多个相同的Controller,路由注册未分开

解决方法:

修改SearchAreaRegistration文件 RegisterArea 方法如下

public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Search_default",
"Search/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional },
new string[] { "MVC.Areas.Search.Controllers" }
);
}

修改RouteConfig文件内 RegisterRoutes 方法如下

public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces:new []{" MVC .Controllers"}
);
}

标签: MVC Areas Route 阅读: 16632
上一篇: 使用SqlCacheDependency依赖项让数据库变化后缓存失效 - 11095次
下一篇: MVC4使用[Authorize(Roles="admin")]验证时报数据库连接错误 - 219070次

网友评论

momy 2013/1/20 16:35:16

如果出现“Named argument specifications must appear after all fixed arguments have been specified”说明你RouteConfig文件里边少了“namespaces:”,其他文件可以不用这个。

向右滑动解锁留言