簡體   English   中英

使用 HttpServletRequest 的 Swagger 文檔

[英]Using Swagger Documentation for HttpServletRequest

我是 swagger 的新手並使用它的文檔。 我目前正在嘗試使用 swagger 來顯示 PATCH 請求的請求正文。 以前,PATCH方法的參數是正在更新的object的DTO,這樣可以很容易地顯示object的屬性(因為我使用的是SpringBoot,並且使用@Schema效果很好)。 但是,現在 PATCH 方法的參數是一個 HttpServletRequest。 我不想在 swagger 文檔中顯示 HttpServletRequest(這似乎是自動發生的),而是想顯示 DTO 屬性(就像之前所做的那樣)。 我想知道是否有辦法做到這一點?

非常感謝任何建議!

我假設您正在使用 springdoc-openapi 來生成 SwaggerUI。

要使用它,您可以使用以下 Maven 依賴項,

<dependency>
  <groupId>org.springdoc</groupId>
  <artifactId>springdoc-openapi-ui</artifactId>
  <version>1.4.2</version>
</dependency>
<dependency>
  <groupId>org.springdoc</groupId>
  <artifactId>springdoc-openapi-webmvc-core</artifactId>
  <version>1.4.2</version>
</dependency>

從 springdoc-openapi v1.1.25 開始,HttpServletRequest 和 HttpServletResponse 將被添加到忽略類型列表中。

見下文,

https://github.com/springdoc/springdoc-openapi/issues/57

因此即使我們在 controller 方法中添加 HttpServletRequest 作為參數,它也會被忽略,不會顯示在 swagger 中。

所以回到你的問題,要顯示 class 的 model,你可以描述另一個參數以及 HttpServletRequest 如下,

@Operation(summary = "Returns a token", description = "Returns A token API", tags = "tokenGeneration", responses = {

            @ApiResponse(description = "Successful Operation", responseCode = "200", content = @Content(mediaType = "application/json", schema = @Schema(implementation = Timeresponse.class))),
            @ApiResponse(description = "not found Operation", responseCode = "404") })
    @PatchMapping("/getTokenPatchRequest")
    public ResponseEntity getTokenpatch(HttpServletRequest request, @RequestBody AuthReq2 req) {

        log.info("The HttpServlet request header contains the information : " + request.getHeader("Authorization"));

Auth2 的 model class 如下,可以描述您的用戶名和密碼等示例值。

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

@Data
public class AuthReq2 {
    
    @Schema(example = "diannamcallister")
    private String userName;
    
    @Schema(example = "test")
    private String password;

}

最后 swagger 頁面看起來像這樣,

在此處輸入圖像描述

當您在授權 header 中輸入內容時,如下所示,

在此處輸入圖像描述

這可以通過以下代碼通過 HTTP servlet 請求訪問,

log.info("The HttpServlet request header contains the information : " + request.getHeader("Authorization"));

springboot 應用程序中的日志條目如下所示,

10:40:01.876 INFO   OpenApiController.getTokenpatch:163 - The HttpServlet request header contains the information : stackoverflow

上面的答案不起作用,因為向方法添加另一個參數會破壞方法本身的功能。

有效的解決方案是在 controller 中將 content 參數添加到@RequestBody注釋中:

@RequestBody(description = "Description.", 
           content = @Content(schema = @Schema(implementation = ObjectDTO.class)));

如何在 swagger 文檔中顯示 HttpServletRequest?

可以在swagger2的配置中設置, SwaggerConfig.java

new Docket(DocumentationType.SWAGGER_2)
                ...
                .ignoredParameterTypes(HttpSession.class, HttpServletRequest.class, HttpServletResponse.class)
                .build();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM