How to implement proper HTTP error handling in .NET MVC 2?

后端 未结 4 608
一个人的身影
一个人的身影 2020-11-29 19:29

I\'ve been struggling all day to implement error handling in my ASP.NET MVC 2 app. I\'ve looked at a variety of techniques, but none work properly. I\'m using MVC2 and .NET

4条回答
  •  孤城傲影
    2020-11-29 19:37

    Here's one technique you could use. Define an ErrorsController which will serve the error pages:

    public class ErrorsController : Controller
    {
        public ActionResult Http404()
        {
            Response.StatusCode = 404;
            return Content("404", "text/plain");
        }
    
        public ActionResult Http500()
        {
            Response.StatusCode = 500;
            return Content("500", "text/plain");
        }
    
        public ActionResult Http403()
        {
            Response.StatusCode = 403;
            return Content("403", "text/plain");
        }
    }
    

    and then in Global.asax you could subscribe for the Application_Error event where you could log the exception and execute the corresponding action of the ErrorsController:

    protected void Application_Error(object sender, EventArgs e)
    {
        var app = (MvcApplication)sender;
        var context = app.Context;
        var ex = app.Server.GetLastError();
        context.Response.Clear();
        context.ClearError();
        var httpException = ex as HttpException;
    
        var routeData = new RouteData();
        routeData.Values["controller"] = "errors";
        routeData.Values["exception"] = ex;
        routeData.Values["action"] = "http500";
        if (httpException != null)
        {
            switch (httpException.GetHttpCode())
            {
                case 404:
                    routeData.Values["action"] = "http404";
                    break;
                case 403:
                    routeData.Values["action"] = "http403";
                    break;
                case 500:
                    routeData.Values["action"] = "http500";
                    break;
            }
        }
        IController controller = new ErrorsController();
        controller.Execute(new RequestContext(new HttpContextWrapper(context), routeData));
    }
    

    And now all that's left is to start throwing proper exceptions:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            throw new HttpException(404, "NotFound");
        }
    }
    

提交回复
热议问题