当前位置 : 主页 > 网络编程 > ASP >

asp.net-mvc – Asp.net mvc 2 – 从ActionFilter重定向错误?

来源:互联网 收集:自由互联 发布时间:2021-06-24
从mvc1和mvc2改变了什么?如果用户未经过身份验证,我有以下代码重定向到登录页面.这不适用于mvc2并导致“System.Web.HttpException:在发送HTTP标头后无法重定向” public class RequiresAuthenticat
从mvc1和mvc2改变了什么?如果用户未经过身份验证,我有以下代码重定向到登录页面.这不适用于mvc2并导致“System.Web.HttpException:在发送HTTP标头后无法重定向”

public class RequiresAuthenticationAttribute : FilterAttribute, IAuthorizationFilter
{
  public 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);
    }
  }
}

堆栈跟踪如下:

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)
您所要做的就是覆盖HandleUnauthorizedRequest而不是OnAuthorization,只需将RedirectResult url分配给AuthorizationContext.Result即可.

base.OnAuthorization将检查身份验证,如果失败则调用HandleUnauthorizedRequest.

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;
}
网友评论