[英]Controller with same name as an area - Asp.Net MVC4
我在主/頂部區域有一個Contacts控制器,我有一個名為“Contacts”的區域。
如果我在注冊頂級路線之前注冊我的區域,我會將POST 404s發送到Contacts控制器:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
ModelBinders.Binders.DefaultBinder = new NullStringBinder();
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
而且,如果我在路線后注冊我的區域,我的404到聯系人控制器就會消失,但我到聯系人區域的路線現在是404s。
...記錄了許多重復的控制器名稱問題,但我沒有找到該區域與控制器名稱相同的特定方案。
...可能很容易解決。 很感激幫助。 :-D
fwiw,我正在使用顯式命名空間注冊我的Contacts區域:
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[] { "MyMvcApplication.Controllers" }
);
}
有兩件事需要考慮
在Application_Start()方法的寄存器區域中首先是AreaRegistration.RegisterAllAreas();
。
在名稱沖突的情況下,使用App_Start文件夾中的文件RouteConfig.cs的命名空間以及在路線中定義的所有路由(如ContactsAreaRegistration.cs)
為了復制您的場景,我創建了一個示例應用程序,並能夠成功訪問以下兩個URL:
http://localhost:1200/Contacts/Index http://localhost:1200/Contacts/contacts/Index
我的應用程序的結構如下:
在ContactsAreaRegistration.cs文件中,我們有以下代碼:
public class ContactsAreaRegistration : AreaRegistration { public override string AreaName { get { return "Contacts"; } } public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( "Contacts_default", "Contacts/{controller}/{action}/{id}", new { action = "Index", id = UrlParameter.Optional }, namespaces: new[] { "MvcApplication1.Areas.Contacts.Controllers" } ); } }
希望它會對你有所幫助。 如果您需要,我可以發送我創建的示例應用程序代碼。 謝謝。
對於MVC5,我做了@Snesh所做的但是沒有完全奏效。 它只會解析我所在區域的控制器,但如果它們具有相同的名稱,則不會解析項目的根目錄。 我最后必須在RouteConfig.cs
的RegisterArea
方法和RegisterRoutes
方法中將命名空間指定為參數。
RouteConfig.cs
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 },
// This resolves to the Controllers folder at the root of the web project
namespaces: new [] { typeof(Controllers.HomeController).Namespace }
);
}
AreaRegistration.cs
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Handheld_default",
"Handheld/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional },
namespaces: new[] { typeof(Areas.Handheld.Controllers.HomeController).Namespace }
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.