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

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

    The only way I could get @cottsak's method to work for invalid controllers was to modify the existing route request in the CustomControllerFactory, like so:

    public class CustomControllerFactory : DefaultControllerFactory
    {
        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            try
            {
                if (controllerType == null)
                    return base.GetControllerInstance(requestContext, controllerType); 
                else
                    return ObjectFactory.GetInstance(controllerType) as Controller;
            }
            catch (HttpException ex)
            {
                if (ex.GetHttpCode() == (int)HttpStatusCode.NotFound)
                {
                    requestContext.RouteData.Values["controller"] = "Error";
                    requestContext.RouteData.Values["action"] = "Http404";
                    requestContext.RouteData.Values.Add("url", requestContext.HttpContext.Request.Url.OriginalString);
    
                    return ObjectFactory.GetInstance();
                }
                else
                    throw ex;
            }
        }
    }
    

    I should mention I'm using MVC 2.0.

提交回复
热议问题