【问题标题】:CustomErrors mode="On" is not redirecting to custom error page in ASP.Net Web API 2.0CustomErrors mode="On" 不会重定向到 ASP.Net Web API 2.0 中的自定义错误页面
【发布时间】:2018-05-21 20:48:43
【问题描述】:

我正在尝试在我们的 Web API 项目中创建一个 customError 页面。如果 API 中发生任何未处理的错误,我需要重定向到某个自定义页面,或者如果路由不可用,那么我还需要重定向到某个自定义错误页面。为此,我在 web.config 文件中添加了以下设置。

<compilation debug="true" targetFramework="4.5" />
<customErrors mode="On" defaultRedirect="~/Error">
  <error statusCode="404" redirect="~/Error"/>
</customErrors>

我在共享文件夹中添加了 Error.cshtml 视图。 (注意:我的项目中没有Error控制器)

但如果我点击任何无效路径,我将获得 IIS 设置 404 页面。请看截图。

不确定,我到底错过了什么。 此外,如果我附加了一个调试器,它不会来自 Global.asax.cs 的 Application_Error 方法(例如 404/501 错误)。令人惊讶。

您的帮助将不胜感激。

【问题讨论】:

  • 自定义错误页面适用于普通的 mvc 控制器而不是 apiControllers,因为 api 控制器不引用视图页面
  • 那有什么选择呢?我怎样才能实现上述场景?
  • 以下链接可能对您有所帮助:link1link2

标签: asp.net asp.net-web-api custom-errors


【解决方案1】:

我今天遇到了同样的问题,并找到了可能对您有所帮助的解决方案。 我想在你的控制器中你正在做这样的事情:

 public ActionResult AddReport
    ... 
    if (something is bad...)
         return HttpNotFound("Hey you have some beautiful error here");

因此,这将返回您在问题中包含的屏幕截图。
解决办法就是这样做

  public ActionResult AddReport
    ... 
    if (something is bad...)
         return new HttpException(404, "Hey you have some beautiful error here");

编辑

根据您的评论,当您已经有很多控制器时,这不是实际的解决方案

在这种情况下,您可以尝试编辑您的 web.config 并将 标签替换为这个

<httpErrors errorMode="Custom">
  <remove statusCode="404"/>
  <error statusCode="404" path="/Error.html" responseMode="ExecuteURL"/>
</httpErrors>

编码愉快!!

【讨论】:

  • 但是我必须对所有操作方法都这样做。这不是实际的解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-27
  • 1970-01-01
  • 2013-08-28
  • 2014-12-23
  • 1970-01-01
相关资源
最近更新 更多