【问题标题】:Response.TrySkipIisCustomErrors equivalent for asp.net core?Response.TrySkipIisCustomErrors 等效于 asp.net 核心?
【发布时间】:2018-08-22 11:44:11
【问题描述】:

如何防止 IIS 使用 IIS 默认错误页面覆盖自定义错误页面?是否有等效于 asp.net 核心的 Response.TrySkipIisCustomErrors? 在 ASP Net MVC 中,我使用下面的代码在没有自定义页面的情况下发送错误,但在 asp net core 中它不起作用。

try
{
    // some code
}
catch (Exception ex)
{
    Response.TrySkipIisCustomErrors = true;
    Response.StatusCode = (int)HttpStatusCode.InternalServerError;
    mensagem = ex.Message;
}

【问题讨论】:

  • 你得到什么错误页面?写入响应正文应该足以避免任何默认页面。
  • 当 IIS 获得 HTTP 状态代码 500 时,它会发送自定义错误页面。我不想发送这个自定义错误页面。
  • 你试过Error Handling in ASP.NET Core的介绍吗?
  • 我知道如何在 asp net core 中创建自定义错误页面,但我希望在某些情况下不重定向到自定义错误页面。示例:我想返回带有状态码 404 的 json,而不是自定义 404 页面。
  • 据我了解,您不希望向用户显示特定 HTTP 状态代码的错误页面。相反,您希望返回 JSON 作为响应。对吗?

标签: asp.net-core


【解决方案1】:

您可以尝试编写一个exception 处理中间件。这是我用作参考的blog post。类似于

    public class ErrorHandlingMiddleware
    {
      private readonly RequestDelegate next;

      public ErrorHandlingMiddleware(RequestDelegate next)
      {
        this.next = next;
      }

      public async Task Invoke(HttpContext context)
      {
        try
        {
            await next(context);
        }
        catch (Exception ex)
        {
            await CustomHandleExceptionAsync(context, ex);
        }
      }

    private static Task CustomHandleExceptionAsync(HttpContext context, Exception exception)
    {

        if (exception is NotFoundException)
        {

         var customJson = JsonConvert.SerializeObject(new{ error = 
         exception.Message });
         context.Response.ContentType = "application/json";
         context.Response.StatusCode = (int)HttpStatusCode.NotFound;
         return context.Response.WriteAsync(customJson);
       }
   }

【讨论】:

  • 这根本没有解决问题。 IIS 拦截状态代码在 400-599 范围内的出站响应 - 您需要指定特殊的响应标头或侧通道来指示 IIS 不拦截和替换响应内容。我相信这段代码对你有用,因为你可能有一个web.config 规则,所以 IIS 不会替换 HTTP 404 响应,但这不适用于 409、5xx 等。
【解决方案2】:

在控制器中:

    public IActionResult Test()
    {
        return NotFound(new { Message = "Hello" });
    }

在 web.config 中:

<system.webServer>
    <security>
        <requestFiltering>
            <fileExtensions>
                <clear />
            </fileExtensions>
        </requestFiltering>
    </security>
    <httpErrors>
        <clear />
    </httpErrors>
</system.webServer>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-10
    • 1970-01-01
    • 2017-12-23
    • 2017-08-04
    • 1970-01-01
    • 2017-10-23
    相关资源
    最近更新 更多