asp.net-web-api - 响应正文未从 swagger Swashbuckle 中的自定义错误响应中返回
问题描述
我已经使用 Swashbuckle 将 swagger 集成到 dot.net 核心 API 应用程序中。当我通过 Swagger UI 执行 API 而不提供凭据时,它会按预期返回“401-未经授权”响应。
但它没有显示我配置为作为正文作为自定义错误响应返回的错误响应。它确实返回如下图所示的标题。
当我通过 Postman 执行相同的 API 时,它会返回自定义错误响应,如下所示。
我需要的是,我还需要在 swagger UI 中查看自定义错误响应正文。
与 403 和 404 状态代码相同的场景。
解决方案
经过一番努力,我找到了问题的根本原因。这是由于没有在“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";" 解决问题。
推荐阅读
- java - 程序无法编译,因为它期望 { before throw in public constructor() throw exception
- python - 对 FeatureUnions (pandas) 工作理解的困惑
- regex - 多个连续空间的模式验证器
- google-analytics - 如何通过 GTM/GA 对两个单独的结帐进行 A/B 测试
- javascript - 等待外部数据的节点 API
- unity3d - Unity不忽略“忽略Raycast”层中的按钮单击
- python - 使用 OpenSSL 和 Python3 签名数据 - 无法验证签名数据
- python - 按 ID 分组类别 python
- f# - 如何抽象出 Int32 和 Int64 类型的方法?
- amazon-web-services - Dynamodb 表设计模式