ASP.NET MVC和不同的404页面用于不同的控制器

时间:2014-01-18 16:00:20

标签: c# asp.net asp.net-mvc http-status-code-404

我想为特定控制器显示不同的404页面,然后使用我现在的默认值。我怎样才能做到这一点?现在是我的设置:

 protected void Application_Error()
        {
            if (!Request.IsLocal)
            {
                var context = new HttpContextWrapper(HttpContext.Current);

                if (!context.Request.IsAjaxRequest())
                {
                    context.Response.ContentType = "text/html";

                    var unhandledException = Server.GetLastError();
                    var httpException = unhandledException as HttpException;
                    if (httpException == null)
                    {
                        var innerException = unhandledException.InnerException;
                        httpException = innerException as HttpException;
                    }

                    Server.ClearError();
                    var routeData = new RouteData();

                    routeData.Values.Add("controller", MVC.Errors.Name);

                    if (httpException != null)
                    {
                        var httpCode = httpException.GetHttpCode();
                        switch (httpCode)
                        {
                            case (int) HttpStatusCode.NotFound:
                                routeData.Values.Add("action", "PageNotFound");

                                IController pageNotFoundController = new ErrorsController();
                                pageNotFoundController.Execute(new RequestContext(context, routeData));
                                break;
                        }
                    }
                    else
                    {
                        routeData.Values.Add("exception", unhandledException);
                        routeData.Values.Add("action", "Error");
                        IController errorController = new ErrorsController();
                        errorController.Execute(new RequestContext(context, routeData));
                    }
                }
            }
        }

1 个答案:

答案 0 :(得分:0)

     public class ErrorController : Controller {
         publc ActionResult NotFound()
         {
           Return View();
          }
      }

      <customErrors mode="On">
         <error statusCode="404" redirect="~/Error/NotFound"/>
      </customErrors>

在NotFound Action中,您可以指定逻辑。我希望这会对你有所帮助。