开发者

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

开发者 https://www.devze.com 2023-01-06 20:54 出处:网络
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.

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

精彩评论

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