MVC2 ActionFilterAttribute – During OnActionExecuting Don't use Redirect Use RedirectResult

28 באפריל 2010

Still haven't upgraded to the visual studio 2010 RTM, so I'm talking about version RC1 of MVC2(the one that shipped with VS2010 RC),
But i guess this is also the case with the RTM version.

We followed the excellent post by Rob Conery and implemented our own ActionFilterAttribute
to validate that only authenticated users gain access to some of the actions.
At OnActionExecuting we checked for anonymous users and redirected them to the login page.

All went well till Accidentally i stumbled upon an exception right before the user was redirected to the login page,
users will never see this exception, but the server will suffer.
i usually check the "Remember Me" checkbox to save time…
(it is always a good idea to check the "Thrown" checkbox for the "Common Language Runtime Exceptions"
at the Exceptions window => click on Ctrl+Alt+e to open it).

It turns  out that calling filterContext.HttpContext.Response.Redirect(loginUrl, true);
will redirect to the requested Url, but it doesn't stop the Action execution,
so the Action is called and also the OnActionExecuted(of the controller) event is called.

In my case i had an exception at one of the actions trying to get some user data,
and then an exception at OnActionExecuted where i set expiration headers on the request
(got the"Server cannot append header after HTTP headers have been sent.").

The solution:
Use filterContext.Result = new RedirectResult(sUrl); instead of the redirect.
this will skip the Action and of course redirect to the Url.

Note that although the requested Action was skipped, OnActionExecuted will be executed,
but the filterContext.Canceled property will be set to true so you can stop unwanted execution inside it as well

hope this helps.

הוסף תגובה
facebook linkedin twitter email

כתיבת תגובה

האימייל לא יוצג באתר. שדות החובה מסומנים *

4 תגובות

  1. Shay Friedman29 באפריל 2010 ב 6:49

    Why don't you use AuthorizeAttribute?

    הגב
  2. Avi Pinto29 באפריל 2010 ב 10:06

    Hi Shay,

    the point of this post wasn't the authentication but the right way to redirect from an ActionFilterAttribute

    concerning the AuthorizeAttribute,

    we are not using forms authenticahion nor the membership

    so by using it we would have to derive from it, conform to it's limitations(user roles are comma delimited strings),

    implement everything(as we already did) + override the forms authentication module to grab the returned 401 result and redirect to the Login Url

    it is much much simpler to take Robs approach(posted a link to his post), and just use the right redirect

    הגב
  3. Rotem Bloom15 באוקטובר 2010 ב 17:56

    אחלה של דבר תודה.

    הגב
  4. Avi Pinto15 באוקטובר 2010 ב 20:00

    בכיף 🙂

    הגב