我正在尝试为我的ASP.NET(.NET Framework 4.7)MVC 5 Web应用程序实现自定义错误页面。
不幸的是,没有重定向,我无法获得自定义错误页面。我总是收到以下错误:
System.Web.HttpException(0x80004005):找不到路径'/ test'的控制器或未实现IController。
具有重定向设置(将redirectMode="ResponseRewrite"
替换为defaultRedirect="~/Error/GenericError"
),找不到的页面将重定向到错误页面。但是,出于逻辑/语义/ SEO原因,我不希望重定向(例如,未找到错误页面[redirect],而是用户打开的页面)。但这不是讨论的问题。
如何在不进行重定向的情况下实现自定义错误页面?
目录结构
/
Controllers/
ErrorController.cs
HomeController.cs
Views/
Error/
404.cshtml
Home/
Index.cshtml
Web.config
/Web.config (摘自不相关的部分,例如log4net配置部分)
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<customErrors mode="On" redirectMode="ResponseRewrite">
<error statusCode="404" redirect="~/Error/Error404" />
</customErrors>
</system.web>
<system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="404" />
<error statusCode="404" responseMode="ExecuteURL" path="~/Error/Error404" />
</httpErrors>
</system.webServer>
</configuration>
/Controllers/ErrorController.cs
using System.Web.Mvc;
namespace WebApplication1.Controllers
{
[HandleError]
public class ErrorController : Controller
{
public ActionResult Error404()
{
return View("404");
}
}
}