Asp.net mvc 2 - Redirect error from ActionFilter?

What has changed from mvc1 and mvc2? I have the following code that redirects to the login page if the user has not authenticated. This does not work with mvc2 and results in a "System.Web.HttpException: cannot be redirected after sending HTTP headers"

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

The 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)
+3
source share
1 answer

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

The base .OnAuthorization will verify authentication and will 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;
}
+7
source

Source: https://habr.com/ru/post/1725870/


All Articles