【发布时间】:2014-03-07 18:18:09
【问题描述】:
出现错误时,我正在尝试重定向到自定义页面。于是我在Web.Config添加了如下代码
<customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="~/Views/Error/Error500.cshtml">
<error statusCode="404" redirect="~/Views/Error/Error404"/>
<error statusCode="500" redirect="~/Views/Error/Error500"/>
</customErrors>
</system.web>
<system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="404" subStatusCode="-1" />
<error statusCode="404" path="~/Views/Error/Error404" responseMode="ExecuteURL" />
<remove statusCode="500" subStatusCode="-1" />
<error statusCode="500" path="~/Views/Error/Error500" responseMode="ExecuteURL" />
</httpErrors>
但是当我尝试使用 localhost:23920/aFakeURl 时,它会将我重定向到一个空白页面,并且无法到达我的 ErrorController。
如果我尝试 localhost:23920/Error/Error404 它会进入我的控制器
// GET: /Error/Error404
public ActionResult Error404()
{
Response.StatusCode = 404;
return View();
}
然后它返回一个statusCode 404 并且 IIS 不知道如何处理它,它给了我一个空白页。所以我很确定问题出在Web.Config 中的路径。
我试过了
~/Views/Error/Error404"-
~/Views/Error/Error404.cshtml" /Views/Error/Error404"/Views/Error/Error404.cshtml"
值得一提的是,当路径没有 ~ 时,它会返回运行时异常而不是空白页。
所以我有两个问题。
-
Web.Config的正确写法是什么? - 我应该像这样返回正确的状态码吗
Response.StatusCode = 404;在ErrorController?
谢谢
我不知道是否值得一提,但我使用Elmah 进行错误处理和记录。不知道它是否与这个问题有关,但我在他们的文档中读到它应该与mode="On" 一起使用。有没有更好的方法来处理这一切?
编辑
现在我用这个
<customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="/Error/Error500">
<error statusCode="404" redirect="/Error/Error404"/>
<error statusCode="500" redirect="/Error/Error500"/>
</customErrors>
</system.web>
<system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="404" subStatusCode="-1" />
<error statusCode="404" path="/Error/Error404" responseMode="ExecuteURL" />
<remove statusCode="500" subStatusCode="-1" />
<error statusCode="500" path="/Error/Error500" responseMode="ExecuteURL" />
</httpErrors>
但是当我输入错误的 url 时它总是返回错误 500。
例外是System.Web.HttpException: The controller for path '/aBadUrllllll' was not found or does not implement IController.
为什么不返回 404 错误?
我是否必须更改 Route.config 中的某些内容?
【问题讨论】:
-
尝试 defaultRedirect = "~/Error/Error404"。我认为应该重定向到动作,而不是物理路径
-
customError 也一样吗?我还有一个空白页:(
-
您是否也将“redirect="~/Views/Error/Error404”更新为操作?
-
是的。 “~/Error/Error404”的所有内容
-
它可能与redirectMode="ResponseRewrite"有关。 ben.onfabrik.com/posts/aspnet-mvc-custom-error-pages
标签: c# asp.net-mvc iis asp.net-mvc-5