【问题标题】:NSwag: 404 Not Found /swagger/v1/swagger.json on IISNSwag:在 IIS 上找不到 404 /swagger/v1/swagger.json
【发布时间】:2019-07-29 21:59:39
【问题描述】:

我有一个基本的 asp.net core 2.1 Web API。我安装了 NSwag.ASPNetCore nuget 包。

这是我的 startup.cs。当我在 IIS Express 上运行它时,swagger 工作正常。 一旦我将它部署到 IIS,我就找不到 404。 我需要在某处添加路径吗?

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
        {
            builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader();
        }));

        services.AddMvc();
        // Add framework services.
        services.AddMvc()
            .AddJsonOptions(options =>
            {
                options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

        //Add Application Services
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.AddSwaggerDocument();

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseCors("CorsPolicy");

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseSwagger();
        app.UseSwaggerUi3();
        app.UseMvc();
    }
}

【问题讨论】:

标签: swagger asp.net-core-webapi asp.net-core-2.1 nswag


【解决方案1】:

正如 Rico 在下面提到的:升级到 nswag v13 应该可以解决问题(对我来说它有效)。

对于 v13 之前的 nswag 版本:

我遇到了同样的问题,我在这里找到了解决方案:NSwag Issue #1914 您需要做的是配置“转换为外部路径”:

app.UseSwaggerUi3(config =>
{
    config.TransformToExternalPath = (s, r) =>
    {
        string path = s.EndsWith("swagger.json") && !string.IsNullOrEmpty(r.PathBase)
            ? $"{r.PathBase}{s}"
            : s;
        return path;
    };
});

这对我的 iisexpress 和 iis 都有效。

【讨论】:

【解决方案2】:

检查您是否没有为应用程序使用Virtual Path。 Swagger 默认检查绝对路径而不是 localhost:port/MyVirtualPath/swagger/v1/swagger.json

当您使用带有虚拟路径分隔符的 IIS 服务器时,可能会发生这种情况。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-23
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-31
    • 2015-10-01
    • 2019-11-24
    相关资源
    最近更新 更多