开发者

ASP.NET MVC exclude all but an area

In Global.asax, how can I intercept 开发者_C百科all the calls to any action/method but those to a certain area and redirect all the blocked calls to an error page?


The easiest way is probably to update the routes so that the controller is hardcoded and part of the URL template rather than using the default route that can use any controller.

If you want a custom error page rather than 404, add another route that will match anything and also has a hardcoded controller and action.

You could also filter by URL in Application_BeginRequest, but that is likely more work than the two lines of code required for the routing.


Areas are just a nice way to organize your code and separate out the routes that belong to that area. With that said you don't necessarily have to look for a certain area, but the routes that will match the actions in that area. So if you have an Admin area you might have a route like:

context.MapRoute(
            "AdminRoute",
            "Admin/{controller}/{action}",
            new { controller = "Admin", action = "Index" });

You know this is an admin area route since you should know which routes will call the actions in the Admin area controllers. If you want to take this route above as an example and redirect to an error page you could use a wildcard route:

context.MapRoute(
            "AdminErrorRoute",
            "Admin/{*url}",
            new { controller = "Error", action = "Error" });

This will take any route that begins with /Admin and redirect them to an error page. Not sure why you would want to redirect all users to an error page for an entire area. If you just want it on a user by user basis, then look into using an attribute filter on the controller action to determine if the user should be redirected to the error page. Something like this:

[IsUserAdmin()]
public ActionResult Index() { .. }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜