Redirect in FileAttribute's OnActionExecuting not properly working
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 do开发者_JAVA百科n'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()
{
....
}
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.
精彩评论