当从另一个项目内部提供 api 时,如何在 Swashbuckle/Swaggerwork 中创建 url 路径?

How can I make url path in Swashbuckle/Swaggerwork when api is served from inside another project?

全部。我正在尝试使用 Swashbuckle 包记录 WebApi 2。

如果 API 本身就是 运行,即 localhost/api/swagger 将我带到 ui 和 localhost/api/swagger/docs/v1 到 json.

然而,生产应用程序通过 运行 webapiconfig 方法初始化同一个 Webapi 项目,来自 global.asax.cs 另一个 - 现在的 web 项目(主要应用一)。所以 api url 看起来像 localhost/web/api 而不是 localhost/api.

现在 swashbuckle 根本不是那样工作的。

我试图到处寻找,但我找到的只是解决方法。

c.RootUrl(req => req.RequestUri.GetLeftPart(UriPartial.Authority) + VirtualPathUtility.ToAbsolute("~/").TrimEnd('/'));

不幸的是,它不起作用,现在也许它应该起作用,我只需要改变一些东西,但我什至不知道这个 属性 到底期望什么以及应该设置什么。

可能它甚至不适用 - 也许设置我们需要 uires 其他东西或一些虚张声势的代码更改。

如果您能提供任何帮助,我将不胜感激。我真的开始喜欢 swagger(和 swashbuckle)来获取 rest 文档。

为了虚张声势5.x:

这似乎是由 an extension method of httpConfiguration called EnableSwagger. Swashbuckle 5.x migration readme 设置的,注意这会替换 SwaggerSpecConfig。 SwaggerDocConfig RootUrl() 专门替换了 4.x.

中的 ResolveBasePathUsing()

这实际上和以前一样工作,看起来最大的变化是它被重命名并移动到 SwaggerDocConfig:

public void RootUrl(Func<HttpRequestMessage, string> rootUrlResolver)

来自 readme 的示例,为简洁起见进行了调整:

string myCustomBasePath = @"http://mycustombasepath.com";

httpConfiguration
    .EnableSwagger(c =>
        {
            c.RootUrl(req => myCustomBasePath);

            // The rest of your additional metadata goes here
        });

为了虚张声势4.x:

使用 SwaggerSpecConfig ResolveBasePathUsing 并让您的 lambda 读取您的已知端点。

ResolveBasePathUsing:

public SwaggerSpecConfig ResolveBasePathUsing(Func<HttpRequestMessage, string> basePathResolver);

我的 API 在负载平衡器后面,这是提供基地址的有用解决方法。这是一个使用 ResolveBasePathUsing 来解析具有已知基本路径的路径的愚蠢示例。

string myCustomBasePath = @"http://mycustombasepath.com";

SwaggerSpecConfig.Customize(c =>
{
    c.ResolveBasePathUsing((req) => myCustomBasePath);
}

为了清楚起见,我对端点进行了硬编码,但您可以在任何地方定义它。您甚至可以 use the request object to attempt to cleanup your request uri 指向 /web/api 而不是 /api.

开发商 commented on this workaround 于 GitHub 去年:

The lambda takes the current HttpRequest (i.e. the request for a given Swagger ApiDeclaration) and should return a string to be used as the baseUrl for your Api. For load-balanced apps, this should return the load-balancer path.

The default implementation is as follows:

(req) => req.RequestUri.GetLeftPart(UriPartial.Authority) +  req.GetConfiguration().VirtualPathRoot.TrimEnd('/');

...

Re relative paths, the Swagger spec requires absolute paths because the URL at which the Swagger is being served need not be the URL of the actual API.

...

The lambda is passed a HttpRequestMessage instance ... you should be able to use this to get at the RequestUri etc. Another option, you could just place the host name in your web.config and have the lambda just read it from there.