c# - “无法从 http://localhost:52056/undefined 读取 swagger JSON”?
问题描述
Swagger 在我的 Web API 2.2 应用程序中运行良好,网址如下:http://localhost:52056/swagger。但是,我最近更新了解决方案以支持版本控制,因此该解决方案现在支持 api/v1/ 和 api/v2/。现在,当 Swagger 页面加载时,我使用的 Swagger url 返回以下错误:
我应该如何更新 SwaggerConfig.cs 以支持不同 API 版本的 Swagger?这是我当前的 SwaggerConfig.cs:
using System.Web.Http;
using WebActivatorEx;
using Janus.SecurityApi.Api;
using Swashbuckle.Application;
using System.Configuration;
[assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")]
namespace SecurityApi.Api
{
public class SwaggerConfig
{
public static void Register()
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.RootUrl(req => GetRootUrlFromAppConfig());
c.Schemes(new[] { GetSchemeFromAppConfig() });
c.SingleApiVersion("v1", "Security API");
c.IncludeXmlComments(
string.Format(
@"{0}\App_Data\SecurityApi.Api.xml",
System.AppDomain.CurrentDomain.BaseDirectory));
c.IncludeXmlComments(
string.Format(
@"{0}\App_Data\SecurityApi.Core.xml",
System.AppDomain.CurrentDomain.BaseDirectory));
})
.EnableSwaggerUi(c =>
//for non-public sites, error widget will display
//at bottom of swagger page unless disabled
c.DisableValidator()
);
}
private static string GetRootUrlFromAppConfig()
{
return ConfigurationManager.AppSettings["swaggerBaseUrl"];
}
private static string GetSchemeFromAppConfig()
{
return ConfigurationManager.AppSettings["swaggerScheme"];
}
}
}
解决方案
而不是SingleApiVersion
你需要使用MultipleApiVersions
c.MultipleApiVersions(
(apiDesc, targetApiVersion) => targetApiVersion.Equals("default", StringComparison.InvariantCultureIgnoreCase) || // Include everything by default
apiDesc.Route.RouteTemplate.StartsWith(targetApiVersion, StringComparison.InvariantCultureIgnoreCase), // Only include matching routes for other versions
(vc) =>
{
vc.Version("default", "Swagger_Test");
vc.Version("v1_0", "Swagger_Test V1_0");
vc.Version("v2_0", "Swagger_Test V2_0");
});
查看项目页面上的示例:
Swashbuckle/blob/master/README.md#describing-multiple-api-versions
UnitTests 上还有一个示例:
Swashbuckle/blob/master/Swashbuckle.Tests/Swagger/CoreTests.cs#L457
推荐阅读
- electron - 在 Electron 中打开 sqlite3 数据库
- reactjs - 尝试渲染组件时类型无效
- python - 如何在 Python dash 的侧边栏中添加图标
- sockets - SNMP Passthru 问题看不到返回值
- laravel - laravel-inertia 中的 vue-moment 问题
- flutter - 掌握颤振包装布局
- bash - Shell / Bash - 如果我能找到文件,我怎样才能将它们复制到映射驱动器?
- python - 如何在 setup.py 中指定 Python 包的 CPU 架构?
- javascript - 如何读取 js 应用程序的 firebase 中的最后一个消息节点?
- python - 从 Django Admin 一次添加到多个外键