Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 3 routing: prevent ~/home access?

I'm fine with ~/ mapping to Home Index, and with ~/Blog mapping to Blog Index, but how do I prevent ~/Home mapping to Home Index as well? I don't want routes to be accessible from more than a single endpoint.

Similarly, how do I prevent every other "Index" action being accessible from both ~/Controller and ~/Controller/Index?

OK ~/
NO ~/Home
NO ~/Home/Index
OK ~/AnyOtherController
NO ~/AnyOtherController/Index

I guess the rule should be something like preventing any default actions to be accessible explicitly, and in the case of home also prevent it being accessible with just the controller.

Can this be done? Has it been done in the past? SO for instance doesn't do this (you can access either here or there) and both render the home page; and they probably have a different default action name than "index", which possibly is probably an accessible route too.

like image 420
bevacqua Avatar asked Apr 04 '12 16:04

bevacqua


2 Answers

You can simply declare that routing should not be applied to URLs that match there patterns. For example:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.Ignore("Home/{*pathInfo}");
    routes.Ignore("{controller}/Index");
}

A URL matching these routes would then be treated as a bare page, which of course will not exist.

like image 56
Jon Avatar answered Nov 16 '22 16:11

Jon


Implemented it like this in order for those routes to be regarded as 404 errors but still within my MVC application (in order for the custom errors view to take place):

    /// <summary>
    /// By not using .IgnoreRoute I avoid IIS taking over my custom error handling engine.
    /// </summary>
    internal static void RegisterRouteIgnores(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "IgnoreHome",
            "Home",
            new { controller = "Error", action = "NotFound" }
        );

        routes.MapRoute(
            "IgnoreIndex",
            "{controllerName}/Index/{*pathInfo}",
            new { controller = "Error", action = "NotFound" }
        );

This does allow access to Home/Index action through the use of /home/{id}, but I'm willing to live with that.

like image 4
bevacqua Avatar answered Nov 16 '22 16:11

bevacqua