HTTP错误404.0 - 在MVC 5中找不到

Anj*_*jyr 2 c# asp.net custom-error-pages http-status-code-404 asp.net-mvc-5

我在MVC 5.i的项目想要handel 404.我做到了,但问题是

当我使用以下URL访问视图时,一切正常并且符合预期:

http://localhost/Hotels/Index30701000000
Run Code Online (Sandbox Code Playgroud)

但是当我使用以下URL访问视图时,我收到404.0错误消息(错误如下所示)

http://localhost/Hotels/Edit/09099999dfdfb                       
http://localhost/Hotels/Edit/090/20130701000000
Run Code Online (Sandbox Code Playgroud)

错误:HTTP错误404.0 - 未找到您要查找的资源已被删除,名称已更改或暂时不可用.

我的代码是

调节器

public class ErrorController : Controller
{
    // GET: Error
    public ActionResult Unauthorized()
    {
        Response.StatusCode = 404;
        Response.TrySkipIisCustomErrors = true;
        return View();
    }
}
Run Code Online (Sandbox Code Playgroud)

RouteConfig

    routes.MapRoute(
        name: "Unauthorized",
        url: "Unauthorized/{action}/{id}",
        defaults: new
        {
            controller = "Error",
            action = "Unauthorized",
            id = UrlParameter.Optional
        }
    );
Run Code Online (Sandbox Code Playgroud)

Global.asax中

    protected void Application_Error()
    {
        Exception exception = Server.GetLastError();
        HttpException httpException = exception as HttpException;
    }
Run Code Online (Sandbox Code Playgroud)

webconfig

  <system.web>
    <customErrors mode="On" defaultRedirect="Error">
      <error statusCode="404" redirect="Unauthorized" />
    </customErrors>
  </system.web>
Run Code Online (Sandbox Code Playgroud)

查看 //Unauthorized.cshtml

@model System.Web.Mvc.HandleErrorInfo
@{
    ViewBag.Title = "Unauthorized";
}
<h1>Page Not Found!</h1>
Run Code Online (Sandbox Code Playgroud)

参考链接

Eri*_*ric 5

另一种方法是在ErrorController中定义错误页面,然后在web.config中的system.WebServer下使用httpError部分.

<httpErrors errorMode="Custom" existingResponse="Replace">
  <remove statusCode="404" />
  <error statusCode="404" responseMode="ExecuteURL" path="/Error/NotFound" />
  <remove statusCode="500" />
  <error statusCode="500" responseMode="ExecuteURL" path="/Error/Error" />
</httpErrors>
Run Code Online (Sandbox Code Playgroud)

上面的代码是您可以测试您的自定义页面.但是在开发环境中,您可以使用errorMode ="DetailedLocalOnly"和existingResponse ="Auto"替换Custom,这样您仍然可以看到详细信息错误.

我最近写了一篇关于它的帖子,它附带了一个可以在GitHub上使用的示例演示项目.http://www.neptunecentury.com/Blogs/ASP-NET/MVC5/MVC-5-How-To-Show-Custom-Error-Pages