代码之家  ›  专栏  ›  技术社区  ›  Jsinh

使用Swashback Aspnetcore向swagger.json添加'host'、'basePath'和'schemes'

  •  1
  • Jsinh  · 技术社区  · 7 年前

    Get started with Swashbuckle and ASP.NET Core

    如果我查看生成的swagger.json文件,它缺少三个重要属性 host basePath schemes

    基本路径 如果遵循应用程序中的文档代码,则缺少的值

    {
      "swagger": "2.0",
      "info": {
        "version": "v1",
        "title": "Demo API Title"
      },
      "host": "some-url-that-is-hosted-on-azure.azurewebsites.net",
      "basePath": "/api",
      "schemes": ["https"],
      "paths": {
        "/Account/Test": {
          "post": {
            "tags": [
              "Admin"
            ],
            "summary": "Account test method - POST",
            "operationId": "AccountTest",
            "consumes": [],
            "produces": [
              "text/plain",
              "application/json",
              "text/json"
            ],
            "parameters": [],
            "responses": {
              "200": {
                "description": "Success",
                "schema": {
                  "type": "boolean"
                }
              }
            }
          }
        }
      },
      "definitions": {
        "NumberSearchResult": {
          "type": "object",
          "properties": {
            "number": {
              "type": "string"
            },
            "location": {
              "type": "string"
            }
          }
        }
      },
      "securityDefinitions": {
        "Bearer": {
          "name": "Authorization",
          "in": "header",
          "type": "apiKey",
          "description": "Authorization. Example: \"Authorization: Bearer {token}\""
        }
      },
      "security": [
        {
          "Bearer": []
        }
      ]
    }
    
    1 回复  |  直到 7 年前
        1
  •  19
  •   Ameya    6 年前

    .netcore的最新版本Swashback中有一些更改

    如果您希望更改Swashback中的请求URL,可能您在API网关后面,或者将自定义域附加到您的webapp。这样做。

    public class BasePathDocumentFilter : IDocumentFilter
        {
            public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
            {
                swaggerDoc.Servers = new List<OpenApiServer>() { new OpenApiServer() { Url = "hxxt://yoursite" } };
            }
        }
    
    1. 在启动文件中 services.AddSwaggerGen() c.DocumentFilter<BasePathDocumentFilter>();
        2
  •  10
  •   Tseng    7 年前

    您可以实现并注册自己的 IDocumentFilter 并在此处设置所需的值。

    public class MyDocumentFilter : IDocumentFilter
    {
        public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
        {
            swaggerDoc.Host = "some-url-that-is-hosted-on-azure.azurewebsites.net";
            swaggerDoc.BasePath = "/api";
            swaggerDoc.Schemes = new List<string> { "https" };
        }
    }
    

    services.AddSwaggerGen(options =>
    {
        options.DocumentFilter<MyDocumentFilter>();
    });
    
        3
  •  7
  •   Francisco Vilches    5 年前

    编辑(2009年9月20日) 下面是一些适用于asp.netcore Swashback库4.x.x版的代码片段

    将来我可能会发表另一篇文章,以防下面的新版本更简单(在撰写本文时是5.x.x版)

    {
      "Logging": {
        "LogLevel": {
          "Default": "Warning",
          "Microsoft.Hosting.*": "Information"
        }
      },
      "Swagger": {
        "ApiVersion": "localhost",
        "ApiName": "v1",
        "SwaggerRelativeUrl": "/swagger/v1/swagger.json",
        "Title": "SalesforceLocationApi"
      }
    }
    

    示例c#代码

        namespace My.Api.Settings
        {
            public class SwaggerSettings
            {
                public string? ApiName { get; set; }
                public string? ApiVersion { get; set; }
                public string? SwaggerRelativeUrl { get; set; }
                public string? Title { get; set; }
            }
        }
    
    
        using Microsoft.AspNetCore.Authentication;
        using Microsoft.AspNetCore.Builder;
        using Microsoft.AspNetCore.Diagnostics;
        using Microsoft.AspNetCore.Hosting;
        using Microsoft.AspNetCore.Http;
        using Microsoft.AspNetCore.Http.Extensions;
        using Microsoft.AspNetCore.Mvc;
        using Microsoft.Extensions.Configuration;
        using Microsoft.Extensions.DependencyInjection;
        using Microsoft.Extensions.Hosting;
        using Microsoft.Extensions.Logging;
        using Newtonsoft.Json;
        using Swashbuckle.AspNetCore.SwaggerGen;
        using Swashbuckle.AspNetCore.SwaggerUI;
        using System;
        using System.Reflection;
        
        namespace My.Api
        {
            public class Startup
            {
                private readonly IConfiguration _configuration;
        
                public Startup(IConfiguration configuration)
                {
                    _configuration = configuration;
                }
        
                public void ConfigureServices(IServiceCollection services)
                {
                    services.AddControllers(ConfigureControllers);
        
                    services
                        .AddSingleton<IHttpContextAccessor, HttpContextAccessor>()
                        .AddSwaggerGen(SetupUpSwaggerGen);
                }
        
                public void Configure(IApplicationBuilder application, IWebHostEnvironment environment, ILoggerFactory loggerFactory, IMapper mapper)
                {
                    if (environment.IsDevelopment())
                    {
                        application.UseDeveloperExceptionPage();
                    }
                    else
                    {
                        application.UseExceptionHandler();
                    }
        
                    application
                        .UseHttpsRedirection()
                        .UseSwagger()
                        .UseSwaggerUI(SetUpSwaggerUi)
                        .UseRouting()
                        .UseAuthorization()
                        .UseEndpoints(endpoints => endpoints.MapControllers());
                }
        
                #region Helpers
        
                private void SetupUpSwaggerGen(SwaggerGenOptions options)
                {
                    var swaggerSettings = _configuration.GetSection("Swagger").Get<SwaggerSettings>();
                    SwaggerConfig.SetUpSwaggerGen(options, swaggerSettings);
                }
        
                private void SetUpSwaggerUi(SwaggerUIOptions options)
                {
                    var swaggerSettings = _configuration.GetSection("Swagger").Get<SwaggerSettings>();
                    SwaggerConfig.SetUpSwaggerUi(options, swaggerSettings.SwaggerRelativeUrl, swaggerSettings.ApiName);
                }
        
                #endregion
            }
        }
    
        using Microsoft.AspNetCore.Builder;
        using Microsoft.AspNetCore.Http;
        using Microsoft.Extensions.DependencyInjection;
        using Microsoft.OpenApi.Models;
        using Swashbuckle.AspNetCore.SwaggerGen;
        using Swashbuckle.AspNetCore.SwaggerUI;
        using System;
        using System.IO;
        using System.Linq;
        using System.Reflection;
        
        namespace My.Api
        {
            public class SwaggerConfig
            {
                internal class SwaggerDocumentFilter : IDocumentFilter
                {
                    private readonly string _swaggerDocHost;
        
                    public SwaggerDocumentFilter(IHttpContextAccessor httpContextAccessor)
                    {
                        var host = httpContextAccessor.HttpContext.Request.Host.Value;
                        var scheme = httpContextAccessor.HttpContext.Request.Scheme;
                        _swaggerDocHost = $"{scheme}://{host}";
                    }
        
                    public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
                    {
                        swaggerDoc.Servers.Add(new OpenApiServer { Url = _swaggerDocHost });
                    }
                }
        
                internal static void SetUpSwaggerGen(SwaggerGenOptions options, SwaggerSettings swaggerSettings)
                {
                    options.DocumentFilter<SwaggerDocumentFilter>();
                    options.SwaggerDoc(swaggerSettings.ApiName, new OpenApiInfo { Title = swaggerSettings.Title, Version = swaggerSettings.ApiVersion });
                    options.CustomSchemaIds(type => $"{type?.Namespace?.Split('.').Last()}.{type?.Name}"); //E.g. Acme.Dtos.Gas.Meter.cs --> Gas.Meter
        
                    AddXmlComments(options);
                }
        
                internal static void SetUpSwaggerUi(SwaggerUIOptions options, string? swaggerRelativeUrl, string? apiName)
                {
                    options.SwaggerEndpoint(swaggerRelativeUrl, apiName);
                }
        
                private static void AddXmlComments(SwaggerGenOptions options)
                {
                    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                    options.IncludeXmlComments(xmlPath);
                }
            }
        }
    

    我使用的是Swashback.AspNetCore Nuget版本4.0.1

    我需要根据应用程序的托管位置动态添加主机。

    这是我的安排

    1. I your startup.cs将IHttpContextAccessor添加到您的服务中

    1. 在您的swagger配置中,添加DocFilter,如下所示: enter image description here enter image description here
        4
  •  5
  •   Enrico    6 年前

    Swagger/open api 3.0及更高版本需要服务器对象。见: https://swagger.io/specification/#server-object

    像这样在你的创业中设置它

    app.UseSwagger(c =>
    {
        c.PreSerializeFilters.Add((swagger, httpReq) =>
        {
            swagger.Servers = new List<OpenApiServer> { new OpenApiServer { Url = $"{httpReq.Scheme}://{httpReq.Host.Value}" } };
        });
    });
    
        5
  •  0
  •   Cyrus Downey    6 年前

    因此,在.net core 3和Open Api中,可以使用-Nswag.AspNetCore版本13.3.2 nuget。

        app.UseOpenApi( configure => { 
            configure.PostProcess = (doc, httpReq) =>
            {
                doc.Servers.Clear(); //... remove local host, added via asp .net core
                doc.Servers.Add(new OpenApiServer { Url = "[YOUR SERVER URL]" });  //... add server
            };
    
        });
    

    从这个github答案中得出: https://github.com/RicoSuter/NSwag/issues/2441#issuecomment-583721522

    推荐文章