views:

20

answers:

1

I'm trying to use a ActionFilterAttribute to redirect users that are not logged in. Although my redirect is working it redirects but it calls all of my ActionResult code first.

Any ideas as to why it doesn't honour the true flag and end the response?

HttpContext.Current.Response.Redirect("~/Logon",true);

Here is my ActionResult:

[RequireLoggedIn]
public ActionResult Create()
{
    return View(_MessageService.GetAllMessageCategories());
}

This is my Attribute:

public class RequireLoggedIn : ActionFilterAttribute
{
   public override void OnActionExecuting(ActionExecutingContext filterContext)
   {
      if (Membership.GetUser() == null)
      {
           //Not logged in so back to the logon page.
           HttpContext.Current.Response.Redirect("~/Logon",true);
           HttpContext.Current.Response.End();
       }
    }
}
+1  A: 

You need to set the filterContext.Result to something non-null to avoid the downstream processing, otherwise MVC doesn't know that you have short-circuited. The simplest approach would be just:

public override void OnActionExecuting(ActionExecutingContext filterContext) {
  if (Membership.GetUser() == null) {
       filterContext.Result = new RedirectResult("~/Logon");
   }
}
Marc Gravell
Thanks for that :)
Andi