问题
In rails I could create a namespace in order to encapsulate views inside a given name ( or URL prefix)
What I want to do is create a namespace (or Area I believe? ) that shall encapsulate all the administrator controllers inside a given name.
For example, I want to create an Admin namespace, where whenever I go to www.myapp.com/admin/ it would get the me the controller admin with the index method, and that whenever I go to www.myapp.com/admin/products it shall call the product controller with the index method and so on because i also want to limit these controllers to a person that must be logged in as in.
URL and routing wise, how can I accomplish the mentioned before?
回答1:
The feature infact is called Areas in asp.net mvc.
You right-click your project in Visual Studio and click add Area.
You'll now have a sub folder with folders for Views, Controllers and a Shared folder. Also a route is added to the project.
Snag:
There is a case where it would cause a problem if you have a HomeController
inside one of your areas as it will conflict with the HomeController
route for the website root. Steven Sanderson has fix for this in his book:
Change your default route to this:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", // Parameter defaults
id = UrlParameter.Optional },
new [] { "MyAppName.Controllers" } // Prioritized namespace
);
See MDSN Articles.
Video on Asp.net Areas.
Good article by Steven Sanderson:
回答2:
The library MvcCodeRouting allows you to organize controllers, views and URLs using namespace hierarchies, it reflects on your controllers and automatically creates the routes for them.
来源:https://stackoverflow.com/questions/5343053/namespaces-equivalent-in-asp-net-mvc