views:

59

answers:

1

I have an action called EditProfile. To secure it I have added a class RequireUserLogin inherited from ActionFilterAttribute. In the OnActionExecuting, when I redirect user to login page, before going to login page, it first execute the EditProfile action code (which i don't expect) and than redirect the user to login page. I want to not come in action code. Currently the only option I have is throw exception. Is there any other options. The code is:

public class RequireUserLogin : ActionFilterAttribute
    {       
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {

            if (string.IsNullOrEmpty(userID))
            {
                filterContext.HttpContext.Response.Redirect("http://localhost/test/login");
            }
            base.OnActionExecuting(filterContext);

}

The EditProfile action is:

[RequireUserLogin()]
public ActionResult EditProfile()
{
  ....
}
+1  A: 

Authorization filters should not be written like normal action filters since they go through a different code path. Best practice here is to subclass AuthorizeAttribute and to override the AuthorizeCore() and HandleUnauthorizedRequest() methods.

In AuthorizeCore(), return true if UserID is OK, otherwise return false.

In HandleUnauthorizedRequest(), set filterContext.Result = new RedirectResult(...). This will short-circuit action invocation, and the framework will automatically redirect as appropriate.

Levi
instead of Response.Redirect, I used RedirectResult and it's working fine.
Adeel