Reasons behind preventing Redirect in ASP.NET MVC child actions

Topics: ASP.NET MVC
Oct 13, 2013 at 2:06 PM
Edited Oct 13, 2013 at 2:08 PM
RedirectResult in ASP.NET MVC stack explicitly checks before Redirecting the response to make sure it is not in the context of a Child Action. see ExecuteResult method here

In ASP.NET Forms you could redirect the response at any point without any hard restriction. Now I am trying to find what has been the rationale for this check.

I suspect it has something to do with principles and mindset of MVC but I cannot figure out what that is exactly.
Coordinator
Oct 24, 2013 at 8:39 PM
Hi,

I have a two-part answer to this question:
  1. I think that most developers would not consider child actions to be "proper" MVC because a view is making decisions about which additional controllers to run. As such, whether that child action does a Redirect or not is likely orthogonal. Having said that, countless developers find child actions to be super useful!
  2. On the technical side, redirects can't work in a child action because much of the response has already been rendered. A redirect is done by sending an HTTP 302 (or 301) status code in the response along with some other HTTP headers. However, an HTTP 200 header has already been written out, as well as a bunch of HTML (from the outer or "main" view). As such, it's too late to change the response from an HTTP 200 to an HTTP 302 (or 301).
Thanks,
Eilon
Marked as answer by shayanelhami on 10/25/2013 at 12:16 PM
Coordinator
Oct 24, 2013 at 9:29 PM
I should add one more thing:

The reason that RedirectResult has a specific check for IsChildAction is that we felt that developers might try to use it within a Child Action, not realizing that it won't work. The error that you might see if we didn't have that check would probably be some super weird error that wouldn't make sense to most developers. So we decided to add what we hope was a friendlier error message saying what doesn't work.

Thanks,
Eilon
Marked as answer by shayanelhami on 10/25/2013 at 12:16 PM
Oct 25, 2013 at 7:16 PM
Thank you Eilon. Technical reasons aside, I think the first point is very valuable too. A good understanding of MVC design principles is something very hard to come by. Internet is full of formal definitions and technical details of MVC implementations but considerably lacks talks about what is right and what is wrong in MVC.
Coordinator
Oct 25, 2013 at 9:32 PM
Indeed. Ultimately, ASP.NET MVC is a tool for developers to build web applications. But as with many tools, there's more than one way to use it. Some people follow the "absolute purist" view of MVC, and that's fine. They won't use Html.Action. But then others say, "meh, I'll still build a cool app that is unit testable" and it doesn't follow every pure view of how an MVC app should be built. But they still end up being productive and build amazing apps.