首页 > 解决方案 > “无法从 http://localhost:52056/undefined 读取 swagger JSON”?

问题描述

Swagger 在我的 Web API 2.2 应用程序中运行良好,网址如下:http://localhost:52056/swagger。但是,我最近更新了解决方案以支持版本控制,因此该解决方案现在支持 api/v1/ 和 api/v2/。现在,当 Swagger 页面加载时,我使用的 Swagger url 返回以下错误:

无法从http://localhost:52056/undefined读取 swagger JSON

我应该如何更新 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"];
        }
    }
}

标签: c#.netasp.net-web-apiswaggerswashbuckle

解决方案


而不是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


推荐阅读