c# - ASP.NET MVC自定义错误处理Application_Error Global.asax?

标签 c# asp.net asp.net-mvc error-handling user-experience

我有一些基本代码来确定我的MVC应用程序中的错误。当前,在我的项目中,我有一个名为Error的 Controller ,该 Controller 具有操作方法HTTPError404()HTTPError500()General()。它们都接受字符串参数error。使用或修改下面的代码。
将数据传递到错误 Controller 进行处理的最佳/正确方法是什么?我想有一个尽可能强大的解决方案。

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

    HttpException httpException = exception as HttpException;
    if (httpException != null)
    {
        RouteData routeData = new RouteData();
        routeData.Values.Add("controller", "Error");
        switch (httpException.GetHttpCode())
        {
            case 404:
                // page not found
                routeData.Values.Add("action", "HttpError404");
                break;
            case 500:
                // server error
                routeData.Values.Add("action", "HttpError500");
                break;
            default:
                routeData.Values.Add("action", "General");
                break;
        }
        routeData.Values.Add("error", exception);
        // clear error on server
        Server.ClearError();

        // at this point how to properly pass route data to error controller?
    }
}

最佳答案

无需为此创建新路由,您只需重定向到 Controller /操作并通过querystring传递信息即可。例如:

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

  HttpException httpException = exception as HttpException;

  if (httpException != null) {
    string action;

    switch (httpException.GetHttpCode()) {
      case 404:
        // page not found
        action = "HttpError404";
        break;
      case 500:
        // server error
        action = "HttpError500";
        break;
      default:
        action = "General";
        break;
      }

      // clear error on server
      Server.ClearError();

      Response.Redirect(String.Format("~/Error/{0}/?message={1}", action, exception.Message));
    }

然后,您的 Controller 将收到您想要的任何东西:
// GET: /Error/HttpError404
public ActionResult HttpError404(string message) {
   return View("SomeView", message);
}

您的方法需要权衡取舍。在这种错误处理中循环时要非常小心。另一件事是,由于要通过asp.net管道来处理404,因此将为所有这些匹配创建 session 对象。对于频繁使用的系统,这可能是一个问题(性能)。

关于c# - ASP.NET MVC自定义错误处理Application_Error Global.asax?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5208218/

相关文章:

c# - EF v1 的加载行为?

c# - 无弹窗语音识别初始化

asp.net - EF缓存: How to detach objects *completely* before inserting them into HttpRuntime cache?

asp.net - 获取未打开的 .aspx 页面中的代码错误

asp.net - 如何在mvc View 中获取~的值?

javascript - 禁用按钮 .Net Core MVC View

c# - 在 C# cf 中显示下一个表单后尝试关闭一个表单

asp.net - Whatsapp 共享链接无法在移动设备上使用

c# - 如果参数为空,则查询返回所有记录

asp.net-mvc - 用于 asp.net mvc 的回形针