How can I properly handle 404 in ASP.NET MVC?

后端 未结 19 2711
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-21 10:14

I am using RC2

Using URL Routing:

routes.MapRoute(
    \"Error\",
     \"{*url}\",
     new { controller = \"Errors\", action = \"N         


        
19条回答
  •  臣服心动
    2020-11-21 10:50

    My shortened solution that works with unhandled areas, controllers and actions:

    1. Create a view 404.cshtml.

    2. Create a base class for your controllers:

      public class Controller : System.Web.Mvc.Controller
      {
          protected override void HandleUnknownAction(string actionName)
          {
              Http404().ExecuteResult(ControllerContext);
          }
      
          protected virtual ViewResult Http404()
          {
              Response.StatusCode = (int)HttpStatusCode.NotFound;
              return View("404");
          }
      }
      
    3. Create a custom controller factory returning your base controller as a fallback:

      public class ControllerFactory : DefaultControllerFactory
      {
          protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
          {
              if (controllerType != null)
                  return base.GetControllerInstance(requestContext, controllerType);
      
              return new Controller();
          }
      }
      
    4. Add to Application_Start() the following line:

      ControllerBuilder.Current.SetControllerFactory(typeof(ControllerFactory));
      

提交回复
热议问题