【问题标题】:How to set swagger basePath in ASP.NET Web Api?如何在 ASP.NET Web Api 中设置 swagger basePath?
【发布时间】:2018-07-20 19:29:24
【问题描述】:

我为 ASP.NET Web 应用程序启用了 Swagger 文档。如何设置basePath?

GlobalConfiguration.Configuration .EnableSwagger(c => { 
    c.SingleApiVersion("v1", "MyApi") .Description("This is my API."); 
    c.IncludeXmlComments($@"{AppDomain.CurrentDomain.BaseDirectory}\bin\MyApi.XML");
}) .EnableSwaggerUi(c => {});

目前生成的API描述如下:

"swagger": "2.0",
"host": "localhost:8080",
"basePath": "/",

我想改成:

"swagger": "2.0",
"host": "localhost:8080",
"basePath": "/myapi",

【问题讨论】:

  • 你能分享一些你的代码吗?
  • 添加对 Swashbuckle nuget 包的引用,该包会自动将 swaggerConfig.cs 文件添加到 App_Start 文件夹。 swagger UI 和 JSON 文档非常好。我只想设置basePath。 GlobalConfiguration.Configuration .EnableSwagger(c => { c.SingleApiVersion("v1", "MyApi") .Description("This is my API."); c.IncludeXmlComments($@"{AppDomain.CurrentDomain.BaseDirectory}\bin\MyApi.XML"); }) .EnableSwaggerUi(c => {});
  • 其他内容默认注释。我只粘贴了当前使用的(未注释的)代码。它太大了,无法在这里粘贴; stackoverflow 不允许。它甚至不允许上传文件。请创建一个新的 ASP.NET Web Api 项目并添加对 swashbuckle 的引用。否则,请给我您的电子邮件 ID,我会将文件通过电子邮件发送给您。
  • 检查 cmets 看看是否有什么突出...我认为您需要的是 RootUrl
  • 在 stackoverflow 上发布问题之前,我尝试了所有方法,但找不到任何解决方案。 RootUrl 的目的是“默认情况下,服务根 URL 是从用于访问文档的请求中推断出来的。但是,可能存在无法正确解决的情况(例如代理和负载平衡环境)。您可以解决此问题通过提供您自己的代码来确定根 URL。”。您是否在您的任何项目中实施了招摇的文档?您知道为 ASP.NET Web API 设置 basePath 的确切解决方案吗?

标签: asp.net-web-api swagger swashbuckle


【解决方案1】:

您需要将 RootUrl 添加到您的配置中,例如:

GlobalConfiguration.Configuration .EnableSwagger(c => { 
    
    c.SingleApiVersion("v1", "MyApi") .Description("This is my API."); 
    
    c.IncludeXmlComments($@"{AppDomain.CurrentDomain.BaseDirectory}\bin\MyApi.XML");
    
    c.RootUrl(req => { return "http://localhost:8080/myapi"; });
    
}) .EnableSwaggerUi(c => {});

【讨论】:

  • 这将 basePath 添加到 swagger 文档,但不是将“/swagger”重定向到“/swagger/ui/index”,而是重定向到“/myapi/swagger/ui/index”,它给出 404错误。我可以直接浏览到“/swagger/ui/index”,但再次出现错误“无法从localhost:7183/myapi/swagger/docs/v1 读取 swagger JSON”。
  • 另一个问题是它只会将“/myapi”添加为 basePath,但不会从各个 API 中删除相同的内容。这可以通过手动编辑 JSON 文档或使用 powershell 更新文档来解决。
  • @Venky 你不应该在 swashbuckle 之外做任何事情,查看 IDocumentFilters 来转换 swagger json
  • 我注释掉了设置 RootUrl;现在我的招摇 UI 又回来了。使用 DocumentFilter 将 basePath 设置为“/myapi”并从每个路径中删除相同的路径。我不知道这是否是正确的做法,但它解决了我所有的问题。非常感谢@HelderSepu。你摇滚。 swaggerDoc.basePath = "/myapi"; var paths = swaggerDoc.paths.ToList(); foreach (var path in paths) { swaggerDoc.paths.Remove(path.Key); swaggerDoc.paths.Add(path.Key.Replace(swaggerDoc.basePath, string.Empty), path.Value); }
猜你喜欢
  • 2019-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-11
  • 2018-04-01
  • 1970-01-01
  • 2022-07-07
  • 2022-11-08
相关资源
最近更新 更多