首页 > 解决方案 > 响应正文未从 swagger Swashbuckle 中的自定义错误响应中返回

问题描述

我已经使用 Swashbuckle 将 swagger 集成到 dot.net 核心 API 应用程序中。当我通过 Swagger UI 执行 API 而不提供凭据时,它会按预期返回“401-未经授权”响应。

但它没有显示我配置为作为正文作为自定义错误响应返回的错误响应。它确实返回如下图所示的标题。

当我通过 Postman 执行相同的 API 时,它会返回自定义错误响应,如下所示。

我需要的是,我还需要在 swagger UI 中查看自定义错误响应正文。

在邮递员中, 在此处输入图像描述

在招摇, 在此处输入图像描述

与 403 和 404 状态代码相同的场景。

标签: asp.net-web-apiswagger-uiswashbuckle

解决方案


经过一番努力,我找到了问题的根本原因。这是由于没有在“app.UseStatusCodePages”中间件中配置响应内容类型。

  // Custom status handling
        app.UseStatusCodePages(async (StatusCodeContext context) =>
        {
            var settings = new JsonSerializerSettings();
            settings.NullValueHandling = NullValueHandling.Ignore;
            settings.Formatting = Formatting.Indented;

            int statusCode = context.HttpContext.Response.StatusCode;
            ***context.HttpContext.Response.ContentType = "application/json";*** // Added this line to solve the issue

            await context.HttpContext.Response.WriteAsync(JsonConvert.SerializeObject(
                new ErrorResponse((HttpStatusCode)statusCode,
                ReasonPhrases.GetReasonPhrase(statusCode)
                ), settings));
        });

不得不添加 "context.HttpContext.Response.ContentType = "application/json";" 解决问题。


推荐阅读