Not including area name in URL results in “The view 'Index' or its master was not found” instead of 404

谁都会走 提交于 2019-12-02 17:46:02

问题


When I use this URL:

http://www.domain.com/Dashboard/Admin/Index

My page works as expected. Dashboard is an MVC Area, Admin is the controller and Index is the view.

If I remove the area name, like this:

http://www.domain.com/Admin/Index

Then I get the following error:

That's only kind-of expected; shouldn't it be a 404?

Why does MVC still successfully locate the controller and attempt to find the view when I don't specify the area?

How do I force it to return 404 when area is not included?

I've tried changing namespaces but it doesn't make a difference.


回答1:


By default the built-in controller factory will find all implementations of matched controllers regardless of namespace. While the view engine will search for the associated view in context of the request (i.e. won't search in an area if the area route has not been matched). In short you need to limit the route engine definitions to only search in 'defined' namespaces, then the 404 will be thrown.

This is accomplished by using an overload of the MapRoute method, and passing the namespaces:

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
    null, // object constraints
    new string[] { "Namespace.Application.Controllers" } // namespaces
);

For experimental purposes to see what the controller factory does with multiple controllers of the same name, try adding another AdminController to the root Controllers folder and then run the same request.



来源:https://stackoverflow.com/questions/18455401/not-including-area-name-in-url-results-in-the-view-index-or-its-master-was-no

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!