如何在 .Net Core Web API 的 swagger 中设置基本路径属性路径、属性、基本、如何在

2023-09-08 09:18:51 作者:曲未終人已散

我在 ASP.Net Core(版本 1.1.2)中构建了一个 Web API,并使用 Swashbuckle.AspNetCore 来生成 swagger 定义.

i've built a Web API in ASP.Net Core (version 1.1.2) and i use the Swashbuckle.AspNetCore for generating the swagger definition.

下面是自动生成的swagger定义的一部分.我想更改路径,使其不包含 /api/ApiName 但它会包含在 basePath 现在是 /

below is a part of the automatically generated swagger definition. i would like to change the paths so it does not include /api/ApiName but it would be included in the basePath which is now /

{
    "swagger": "2.0",
    "info": {
        "version": "v1",
        "title": "ApiName.V1"
    },
    "host": "ApiUrl",
    "basePath": "/api/ApiName",
    "paths": {
        "/": {
            "get": {
                "tags": [
                    "ApiName"
                ],
                .........

所以我想得到的是:

{
    "swagger": "2.0",
    "info": {
        "version": "v1",
        "title": "ApiName.V1"
    },
    "host": "ApiUrl",
    "basePath": "/",
    "paths": {
        "/api/ApiName": {
            "get": {
                "tags": [
                    "ApiName"
                ],
                .........

我们还有一些其他 API 不是用 .Net Core 编写的,它通过添加默认路由解决了同样的问题.我试图通过删除 API 控制器顶部的路由在 .Net 核心上做同样的事情

We have some other APIs which are not written in .Net Core and there it fixed the same issue by adding default routes. I tried to do the same on .Net core by removing the route at the top of the API controller

[Route("api/[Controller]")]

并将其添加到 Startup.cs.然而这并没有奏效.有人知道如何解决这个问题吗?

and adding it to the Startup.cs. however this did not work. Does anyone have any idea on how to fix this?

推荐答案

最后我用这个来解决它:

in the end i used this to fix it:

您可以设置 PreSerializeFilters 来添加 BasePath 和编辑路径.认为会有更优雅的方式,但这是可行的.

you can set the PreSerializeFilters to add both the BasePath and edit the Paths. Thought there would be a more elegant way but this works.

var basepath = "/api/AppStatus";
c.PreSerializeFilters.Add((swaggerDoc, httpReq) => swaggerDoc.BasePath = basepath);


c.PreSerializeFilters.Add((swaggerDoc, httpReq) => {
    IDictionary<string, PathItem> paths = new Dictionary<string, PathItem>();
    foreach (var path in swaggerDoc.Paths)
    {
        paths.Add(path.Key.Replace(basepath, "/"), path.Value);
    }
    swaggerDoc.Paths = paths;
});