开发者

Asp.net mvc 2 - Error redirecting from ActionFilter?

What changed from mvc1 and mvc2? I have the following code that redirects to a login page if the user has not been authenticated. This doesn't work with mvc2 and results in "System.Web.HttpException: Cannot redirect after HTTP headers have been sent"

public class RequiresAuthenticationAttribute : FilterAttribute, IAuthorizationFilter
{
  pu开发者_StackOverflowblic void OnAuthorization(AuthorizationContext filterContext)
  {
    if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
    {
      string redirectOnSuccess = filterContext.HttpContext.Request.Url.AbsolutePath;
      string redirectUrl = string.Format("?ReturnUrl={0}", redirectOnSuccess);
      string loginUrl = System.Web.Security.FormsAuthentication.LoginUrl + redirectUrl;
      filterContext.HttpContext.Response.Redirect(loginUrl, true);
    }
  }
}

A stack track is as follows:

System.Web.HttpException: Cannot redirect after HTTP headers have been sent.
  at System.Web.HttpResponse.Redirect(String url, Boolean endResponse)
  at System.Web.HttpResponseWrapper.Redirect(String url, Boolean endResponse)
  at System.Web.Mvc.RedirectResult.ExecuteResult(ControllerContext context)
  at System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult)
  at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass14.<InvokeActionResultWithFilters>b__11()
  at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation)
  at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass14.<>c__DisplayClass16.<InvokeActionResultWithFilters>b__13()
  at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult)
  at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName)


All you have to do is override HandleUnauthorizedRequest instead of OnAuthorization and just assign the RedirectResult url to the AuthorizationContext.Result.

The base.OnAuthorization will check authentication and call HandleUnauthorizedRequest if it fails.

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
    string redirectOnSuccess = filterContext.HttpContext.Request.Url.AbsolutePath;
    string redirectUrl = string.Format("?ReturnUrl={0}", redirectOnSuccess);
    filterContext.Result = new RedirectResult(redirectUrl);
    return;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜