开发者

Why does my ActionFilterAttribute redirect after the action code is run?

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 ov开发者_运维知识库erride 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();
       }
    }
}


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");
   }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜