Search code examples
asp.net-mvcasp.net-mvc-routing

How to prevent certain internal routes from being accessed by the user?


I have a site with a lot of routes.

Some routes, e.g. /sector-overview are to a specific page that I want the user to see.

Other routes, e.g. /sectoroverview are to an an action that ultimately renders a partial which is included on the homepage.

the second route is only meant to be internal to the application, but if the user types that into their address bar (it's an easy mistake to make), the system sees that as a valid request and it'll return the HTML partial.

I could rename the second route to something like /internal-sectoroverview, but this isn't really fixing the problem, just hiding it.

Is there any way for me to prevent the request from being processed if the user types this? What's the best way for me to deal with this issue?


Solution

  • You can block the route by using route constraints. However, in your case I would decorate your internal Action with [ChildActionOnly] like this:

    [ChildActionOnly]
    public ActionResult Overview()
    {
        return View();
    }
    

    By doing this, the action will be only rendered when using @Html.Action or @Html.RenderAction. If you try to access it through a browser, you'll get an error.

    UPDATE

    To return a 404 instead of an error you can override the OnException method on the controller and handle it there. Something like this:

    protected override void OnException(ExceptionContext filterContext)
    {
        filterContext.ExceptionHandled = true;
        //check if filterContext.Exception was thrown by child action only (maybe by text)
        filterContext.Result = new HttpStatusCodeResult(404);
    }