Swagger UI 导致 HTTP 406 对生成 json 以外的内容类型的操作不可接受的响应

Swagger UI causing HTTP 406 Not Acceptable response for operations producing content types other than json

我有一个用 Jersey 发布并用 Swagger 记录的 REST API,我还有一个使用 API.

的 Swagger UI 安装

几乎我所有的操作都会产生 application/json 并按预期工作,除了一个 GET 操作会产生:'text/plain;charset=utf-8'

当我尝试从 Swagger UI 调用服务时,服务器记录 javax.ws.rs.NotAcceptableException 和 returns 406 响应。如果我从 REST 客户端调用相同的服务,它会按预期工作。

@GET
@Path("/text")
@Produces(MediaType.TEXT_PLAIN + ";charset=utf-8")
@ApiOperation(value= "Return text")
public Response getText(@QueryParam("user") String user) {
    return Response.ok(textService.getTextForUser(user)).build();
}

如果我更改为@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8") 那么它工作正常,但我不想设置错误的内容类型。

问题似乎是 Swagger UI 错误地将 Accept headers 设置为 application/json,正如观察请求所见:

GET /supertext/text?user=1
...
Accept: application/json

使用其余客户端时,Accept header 是:

GET /supertext/text?user=1
...
Accept: */*

为什么 Swagger UI 没有正确设置接受 header?

这个可以配置吗?

好像是swagger ui发现@Produces注解包含单个值的时候把accept header设置为application/json,否则在[=36中渲染下拉列表=] 从可用的内容类型中进行选择。

大摇大摆-ui.js:

opts.responseContentType = $("div select[name=responseContentType]", $(this.el)).val();

当下拉列表不存在时,属性变为未定义。

稍后在代码中,如果 属性 为 null 或未定义,则响应内容类型设置为 application/json:

在swagger.js中:

if (this.type === "POST" || this.type === "GET" || this.type === "PATCH") {
    if (this.opts.responseContentType) {
      responseContentType = this.opts.responseContentType;
    } else {
      responseContentType = "application/json";
    }
  }

所以我的解决方案是修改 swagger-ui.js 中的代码以确保设置了正确的内容类型,方法是探索生成数组并选择第一个元素作为响应内容类型:

In swagger-ui.js替换行:

opts.responseContentType = $("div select[name=responseContentType]", $(this.el)).val();

有:

if($("div select[name=responseContentType]", $(this.el)).val() === undefined) { 
    opts.responseContentType = opts.parent.model.produces[0];
}

else {
    opts.responseContentType = $("div select[name=responseContentType]", $(this.el)).val();
}

我也遇到了同样的问题,但解决方案有所不同。

问题出在不相关的控制器上,其映射定义不正确。

启动 spring-boot 应用程序时,我能够看到如下日志:

([]) Mapping with class UnrelatedController

每当我加载 swagger UI 时,都会发出 swagger 的 API 请求,但是会显示对此 API 的响应,这与 swagger 的预期不符。

因此错误 406

解决方案是更正 UnrelatedController 的映射,一切正常。感谢 Git 历史记录!