如何在Spring Boot 3中声明从”/”重定向到”/swagger-ui/index.html”的OpenApi 3?

huangapple go评论68阅读模式
英文:

OpenApi 3 with Spring Boot 3 - how to declare a redirect from "/" to "/swagger-ui/index.html"?

问题

我们正在将API文档从swagger.yaml文件迁移到控制器中的注释。

这项工作的主要原因是对API的任何更改都需要在多个地方进行工作。需要验证.yaml文件,重新生成并实现接口。有可能代码的更改不会反映在.yaml文件中。

虽然使用**io.swagger.v3.(...)**运行良好,但如果我明确输入完整的URL https://localhost:8443/swagger-ui/index.html,它将解析OpenAPI页面。

但是,如果我输入https://localhost:8443,则会触发以下方法,因为它打印出https://localhost:8443/swagger-ui/index.html,但不会重定向到该页面。

@RestController
public class Controller {    

    @GetMapping(value = "")
    public String index() {
        var baseUrl = ServletUriComponentsBuilder.fromCurrentContextPath().build().toUriString();

        String redirect = String.format("redirect:%s/swagger-ui/index.html", baseUrl);
        System.out.println(redirect);
        return redirect;
    }
    // other methods
}

使用上述方法会在OpenAPI页面中显示"/"端点,这是我不想要的。

英文:

We are migrating the API documentation from a swagger.yaml file to annotations in the controllers.

The main reason for this work is that any changes to the API require work in more than one place. The .yaml file needs to be validated, the interface re-generated and implemented. There is a chance that changes to the code may not be reflected in the .yaml file.

While it is working fine using io.swagger.v3.(...), if I explicitly enter the full URL https://localhost:8443/swagger-ui/index.html it will resolve the OpenAPI page.

But, if I enter https://localhost:8443 the following method is hit as it prints out https://localhost:8443/swagger-ui/index.html but does not redirect to that page.

@RestController
public class Controller {    

    @GetMapping(value = "")
    public String index() {
        var baseUrl = ServletUriComponentsBuilder.fromCurrentContextPath().build().toUriString();

        String redirect = String.format("redirect:%s/swagger-ui/index.html", baseUrl);
        System.out.println(redirect);
        return redirect;
    }
    // other methods
}

Using the method above shows the "/" endpoint in the OpenAPI page, which I don't want.

答案1

得分: 1

要直接从应用程序的根路径访问swagger-ui,而不是重定向的端点,请将以下属性添加到 application.properties 中:

springdoc.swagger-ui.use-root-path=true
英文:

To access swagger-ui directly from the application root path, instead of the endpoint for redirection, add the following property to application.properties:

springdoc.swagger-ui.use-root-path=true

huangapple
  • 本文由 发表于 2023年7月27日 20:59:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76779995.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定