0

In .Net MVC there is an attribute ChildActionOnly that ensures a particular action cannot be retrieved via a GET request directly, and can only be rendered by way of returning a Partial View from another action or view. (see: Using ChildActionOnly in MVC)

If the user attempts to navigate to an action marked as ChildActionOnly they will see the following error:

The action 'actionName' is accessible only by a child request.

Is there a way of detecting this and redirecting to the main page that calls the child action, or redirect to another page to make sure this error doesn't appear and any accidental requests by the user are handled appropriately?

Community
  • 1
  • 1
Steve
  • 9,335
  • 10
  • 49
  • 81
  • If there was, how would you cope with the situation where the child action is called from multiple places? – DavidG Mar 17 '16 at 00:16
  • @DavidG but in that case it's called correctly. This is to handle the edge case where someone navigates directly to the action in the browser. – Steve Mar 17 '16 at 00:17
  • But how would that be possible unless either the developer did something silly or the end user was trying to do something silly/naughty? – DavidG Mar 17 '16 at 00:18
  • 1
    @DavidG `the developer did something silly or the end user was trying to do something silly/naughty` exactly what I'm trying to code for. What's the stop the user going to `controller/childaction` in the browser and getting the error? – Steve Mar 17 '16 at 00:20
  • If that is the case, why do you care what error is being displayed? – DavidG Mar 17 '16 at 00:20
  • @DavidG because I prefer to handle errors that are reasonably expected to happen gracefully. – Steve Mar 17 '16 at 00:21
  • But aren't you just getting the standard error page in production? You should only see the error mentioned above if you have debug turned on. – DavidG Mar 17 '16 at 00:22
  • @DavidG you would still get an error page, I want to redirect to the main page if a child action is requested, that's all. – Steve Mar 17 '16 at 00:23
  • You could probably catch all errors, determine if the error is of the right type and redirect from there. – DavidG Mar 17 '16 at 00:30
  • 1
    You could always create you own attribute based on the code in the [ChildOnlyAttribute](https://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.Mvc/ChildActionOnlyAttribute.cs) and redirect instead of throwing the error –  Mar 17 '16 at 00:34
  • Yes, shame they sealed the class or it would have been easier. – DavidG Mar 17 '16 at 00:36
  • Never mind, the code is so simple, it's probably easier to write your own anyway! – DavidG Mar 17 '16 at 00:38

0 Answers0