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

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

    I really like cottsaks solution and think its very clearly explained. my only addition was to alter step 2 as follows

    public abstract class MyController : Controller
    {
    
        #region Http404 handling
    
        protected override void HandleUnknownAction(string actionName)
        {
            //if controller is ErrorController dont 'nest' exceptions
            if(this.GetType() != typeof(ErrorController))
            this.InvokeHttp404(HttpContext);
        }
    
        public ActionResult InvokeHttp404(HttpContextBase httpContext)
        {
            IController errorController = ObjectFactory.GetInstance();
            var errorRoute = new RouteData();
            errorRoute.Values.Add("controller", "Error");
            errorRoute.Values.Add("action", "Http404");
            errorRoute.Values.Add("url", httpContext.Request.Url.OriginalString);
            errorController.Execute(new RequestContext(
                 httpContext, errorRoute));
    
            return new EmptyResult();
        }
    
        #endregion
    }
    

    Basically this stops urls containing invalid actions AND controllers from triggering the exception routine twice. eg for urls such as asdfsdf/dfgdfgd

提交回复
热议问题