DaveDev
DaveDev

Reputation: 42195

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?

Upvotes: 3

Views: 2120

Answers (3)

eagle779
eagle779

Reputation: 704

I have a similar problem issue that people finding this might also need - I want to return 404 if a certain criteria is met from a function that returns a PartialViewResult. The solution for me was

public PartialViewResult MyFunction()
{
   if( criteria ) {
      Response.StatusCode = 404;
      return null;
   }
}

Upvotes: 0

goenning
goenning

Reputation: 6654

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);
}

Upvotes: 8

Iridio
Iridio

Reputation: 9271

If I understand right you should resolve the problem of the partial not being called using the attribute ChildActionOnly.just for reference if you don't want that a method in your action can be called at all use the NonActionAttribute

Upvotes: 1

Related Questions