“无法从http:// localhost:52056 / undefined读取不可靠的JSON”吗?

时间:2018-06-27 16:05:19

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

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

  

无法从http://localhost:52056/undefined读取大范围的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"];
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您需要使用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