【问题标题】:.Net Mvc: How to fire a error for Application_Error() manage them?.Net Mvc:如何为 Application_Error() 触发错误来管理它们?
【发布时间】:2011-09-21 14:45:56
【问题描述】:

我在 Global.asax 中的 Application_Error() 中管理所有应用错误:

protected void Application_Error(object sender, EventArgs e)
{
    Exception exception = Server.GetLastError();

    Log.LogException(exception);

    Response.Clear();

    HttpException httpException = exception as HttpException;

    RouteData routeData = new RouteData();
    routeData.Values.Add("controller", "Erro");

    if (httpException == null)
    {
        routeData.Values.Add("action", "Index");
    }
    else //It's an Http Exception
    {
        switch (httpException.GetHttpCode())
        {
            case 404:
                //Page not found
                routeData.Values.Add("action", "HttpError404");
                break;
            case 500:
                //Server error
                routeData.Values.Add("action", "HttpError500");
                break;

            // Here you can handle Views to other error codes.
            // I choose a General error template  
            default:
                routeData.Values.Add("action", "General");
                break;
        }
    }

    //Pass exception details to the target error View.
    routeData.Values.Add("error", exception);

    //Clear the error on server.
    Server.ClearError();

    //Avoid IIS7 getting in the middle
    Response.TrySkipIisCustomErrors = true;

    //Call target Controller and pass the routeData.
    IController errorController = new ErroController();
    errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
}

所以,我的应用程序中有一个自定义授权属性来处理未经授权的请求,我想重定向到 Application_Error() 来操作它。

所以,我这样做了:

protected override void HandleUnauthorizedRequest(AuthorizationContext context)
{
    if (context.HttpContext.Request.IsAuthenticated)
    {
        throw new HttpException(403, "Forbidden Access.");
    }
    else
    {
        base.HandleUnauthorizedRequest(context);
    }
}

以这种方式调用Application_Error(),但如此直接地调用异常对我来说似乎很难看,是否存在另一种方式?大家觉得呢?

【问题讨论】:

    标签: c# .net asp.net asp.net-mvc asp.net-mvc-3


    【解决方案1】:

    因为Unauthorized默认不是错误!!! 只需将此方法添加到global.asax

        protected void Application_EndRequest(object sender, EventArgs e) {
            if (Context.Response.StatusCode == 401 || Context.Response.StatusCode == 403) {
            // this is important, because the 401 is not an error by default!!!
                throw new HttpException(401, "You are not authorised");
            }
        }
    

    【讨论】:

      【解决方案2】:

      您不应在 AuthorizeAttribute 内引发异常,因为这可能会导致依赖 AuthorizeAttribute 进行授权检查的代码出现性能问题。 AuthorizeAttribute 用于检查授权是否有效,而不是根据此信息采取行动。这就是为什么原始代码不直接抛出异常的原因——它将任务委托给 HttpUnauthorizedResult 类。

      相反,您应该创建一个自定义处理程序(类似于HttpUnauthorizedResult)来引发异常。这会将检查授权和基于未授权采取行动的逻辑清晰地分为 2 个不同的类。

      public class HttpForbiddenResult : HttpStatusCodeResult
      {
          public HttpForbiddenResult()
              : this(null)
          {
          }
      
          // Forbidden is equivalent to HTTP status 403, the status code for forbidden
          // access. Other code might intercept this and perform some special logic. For
          // example, the FormsAuthenticationModule looks for 401 responses and instead
          // redirects the user to the login page.
          public HttpForbiddenResult(string statusDescription)
              : base(HttpStatusCode.Forbidden, statusDescription)
          {
          }
      }
      

      然后在您的自定义 AuthorizeAttribute 中,您只需在 HandleUnauthorizedRequest 中设置新的处理程序。

      protected override void HandleUnauthorizedRequest(AuthorizationContext context)
      {
          if (context.HttpContext.Request.IsAuthenticated)
          {
              // Returns HTTP 403 - see comment in HttpForbiddenResult.cs.
              filterContext.Result = new HttpForbiddenResult("Forbidden Access.");
          }
          else
          {
              base.HandleUnauthorizedRequest(context);
          }
      }
      

      如果您需要执行与抛出 HttpException 不同的操作,则应继承 ActionResult 并在 ExecuteResult 方法中实现该操作,或使用继承 ActionResult 的内置类之一。

      【讨论】:

        【解决方案3】:

        您的代码很好。默认情况下,如果您调用base.HandleUnauthorizedRequest,它会引发401 异常,该异常会被表单身份验证模块拦截,并且您会被重定向到登录页面(这可能不是所需的行为)。所以你的方法是正确的。

        另外一种可能,如果不想通过Application_Error,直接渲染对应的错误视图:

        protected override void HandleUnauthorizedRequest(AuthorizationContext context)
        {
            if (context.HttpContext.Request.IsAuthenticated)
            {
                context.Result = new ViewResult
                {
                    ViewName = "~/Views/Shared/Forbidden.cshtml"
                };
            }
            else
            {
                base.HandleUnauthorizedRequest(context);
            }
        }
        

        【讨论】:

        • 该类中视图、控制器和其他人的使用名称是我要避免的。将责任推给 Application_Error() 更好,因为将所有内容集中在一个地方。你同意吗?
        猜你喜欢
        • 2010-10-17
        • 1970-01-01
        • 2013-01-22
        • 2010-11-13
        • 2016-11-12
        • 2011-06-30
        • 2013-06-25
        • 2015-03-05
        相关资源
        最近更新 更多