[MVC]ASP.NET MVC Custom Error Handling Application

baacloud免费翻墙vpn注册使用

通过Application_Error对ASP.NET MVC的所有异常进行默认指向,也可以通过webConfig的        <customErrors mode="RemoteOnly" defaultRedirect="\Error\Index">
            <error statusCode="403" redirect="\Error\Http404" />
            <error statusCode="404" redirect="\Error\Http404" />
        </customErrors>

来指定,不过这样的记录日志异常就需要在ErrorController中进行了

转载:http://stackoverflow.com/questions/1171035/asp-net-mvc-custom-error-handling-applicationerror-global-asax

Instead of creating a new route for that, you could just redirect to your controller/action and pass the information via querystring. For instance:

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

Then your controller will receive whatever you want:

// GET: /Error/HttpError404
public ActionResult HttpError404(string message) {
   return View("SomeView", message);
}

There are some tradeoffs with your approach. Be very very careful with looping in this kind of error handling. Other thing is that since you are going through the ASP.NET pipeline to handle a 404, you will create a session object for all those hits. This can be an issue (performance) for heavly used systems.

Cheers,

André Carlucci

赞(0) 打赏
分享到: 更多 (0)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏