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

后端 未结 19 2695
爱一瞬间的悲伤
爱一瞬间的悲伤 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:51

    Adding my solution, which is almost identical to Herman Kan's, with a small wrinkle to allow it to work for my project.

    Create a custom error controller:

    public class Error404Controller : BaseController
    {
        [HttpGet]
        public ActionResult PageNotFound()
        {
            Response.StatusCode = 404;
            return View("404");
        }
    }
    

    Then create a custom controller factory:

    public class CustomControllerFactory : DefaultControllerFactory
    {
        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            return controllerType == null ? new Error404Controller() : base.GetControllerInstance(requestContext, controllerType);
        }
    }
    

    Finally, add an override to the custom error controller:

    protected override void HandleUnknownAction(string actionName)
    {
        var errorRoute = new RouteData();
        errorRoute.Values.Add("controller", "Error404");
        errorRoute.Values.Add("action", "PageNotFound");
        new Error404Controller().Execute(new RequestContext(HttpContext, errorRoute));
    }
    

    And that's it. No need for Web.config changes.

    0 讨论(0)
提交回复
热议问题