c# - 在我的.Net核心API中将自定义序列化器添加到Swagger

标签 c# asp.net-core swagger-ui swashbuckle json-api

我使用的是jsonapi.org JSONAPI 规范,然后使用JsonApiSerializer来完成JSONAPI规范,所以我的响应和请求正文如下:

{    
    "data": {
    "type": "articles",
    "id": "stringId",
    "attributes": {
      "title": "JSON:API paints my bikeshed!"
    }
}

我有一个实体“文章”
看起来像:
public class Article
{
     public string Id { get; set; }
     public string title { get; set; }
}

然后,我尝试使用 Swashbuckle Swagger 来记录我的API,但是在 Swagger UI 中,我的示例请求和响应正文如下所示:
{
     "id": "string",
     "title": "string"
}

I think swagger is ignoring the JsonApiSerializer, there is a way to change the default serializer for swagger and use my own serializer?



我的Startup.cs看起来像:
public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            this.Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc(
                    "v1",
                    new OpenApiInfo
                    {
                        Version = "v1",
                        Title = "HTT API",
                        Description = "HTT API provides methods to handle events",
                        Contact = new OpenApiContact
                        {
                            Name = "htt",
                            Email = "info@htt.com",
                        },
                    });

                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            });


            services.AddAPIDependencies(this.Configuration);
            services.AddControllers().AddNewtonsoftJson(
            options =>
            {
                var serializerSettings = new JsonApiSerializerSettings();
                options.SerializerSettings.ContractResolver = serializerSettings.ContractResolver;
                options.SerializerSettings.Converters.Add(new StringEnumConverter());
            });

            services.Configure<DatabaseSettings>(
            this.Configuration.GetSection(nameof(DatabaseSettings)));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "HTT API V1");
            });

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
  • 网络核心3.1
  • Swashbuckle.AspNetCore 5.0.0
  • 最佳答案

    您可以使用Swashbuckle.AspNetCore.Filters生成示例性的请求和响应。
    从引用的博客文章之一中复制的示例:

    [Route(RouteTemplates.DeliveryOptionsSearchByAddress)]
    [SwaggerRequestExample(typeof(DeliveryOptionsSearchModel), typeof(DeliveryOptionsSearchModelExample))]
    [SwaggerResponse(HttpStatusCode.OK, Type = typeof(DeliveryOptionsModel), Description = "Delivery options for the country found and returned successfully")]
    [SwaggerResponseExample(HttpStatusCode.OK, typeof(DeliveryOptionsModelExample))]
    [SwaggerResponse(HttpStatusCode.BadRequest, Type = typeof(ErrorsModel), Description = "An invalid or missing input parameter will result in a bad request")]
    [SwaggerResponse(HttpStatusCode.InternalServerError, Type = typeof(ErrorsModel), Description = "An unexpected error occurred, should not return sensitive information")]
    public async Task<IHttpActionResult> DeliveryOptionsForAddress(DeliveryOptionsSearchModel search)
    {
    
    注意各种*Example模型的使用。每个此类类型都应实现IExamplesProvider并生成示例数据:
    public class DeliveryOptionsSearchModelExample : IExamplesProvider
    {
        public object GetExamples()
        {
            return new DeliveryOptionsSearchModel
            {
                Lang = "en-GB",
                Currency = "GBP",
                Address = new AddressModel
                {
                    Address1 = "1 Gwalior Road",
                    Locality = "London",
                    Country = "GB",
                    PostalCode = "SW15 1NP"
                },
                Items = new[]
                {
                    new ItemModel
                    {
                        ItemId = "ABCD",
                        ItemType = ItemType.Product,
                        Price = 20,
                        Quantity = 1,
                        RestrictedCountries = new[] { "US" }
                    }
                }
            };
        }
    
    请注意,示例提供程序应返回您在SwaggerResponse属性(例如DeliveryOptionsSearchModel)中指定的类型的实例。
    启用S​​wagger时,不要忘记启用ExamplesOperationFilter:
    services.AddSwaggerGen(c =>
    {
         c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
         c.OperationFilter<ExamplesOperationFilter>();
    }
    
    更新
    该文档似乎有些过时了。
    我必须执行以下操作才能使示例提供程序生效:
    services.AddSwaggerExamplesFromAssemblyOf<DeliveryOptionsSearchModelExample>();
    
    .AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo {Title = "Elsa", Version = "v1"});
        c.ExampleFilters();
    })
    

    关于c# - 在我的.Net核心API中将自定义序列化器添加到Swagger,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59902076/

    相关文章:

    asp.net-core - ASP.Net Core 2.0 - 如何从中间件返回自定义 json 或 xml 响应?

    c# - 如何将 SetBasePath 设置为 Program.Main 上的 dll 位置

    kotlin - 仅使用Kotlin时在Micronaut中生成Swagger/OpenAPI View

    c# - 检查属性的嵌套/层次结构是否为空?

    c# - 文件流创建或追加问题

    c# - 从 C# 运行 Powershell 脚本

    c# - 如何在 ASP.NET Core 的 Swagger 中包含 XML 注释文件

    c# - DataGridView 滚动事件(和 ScrollEventType.EndScroll)

    visual-studio - ASP.NET Core : "The project doesn' t know how to run the profile Docker.“在 Visual Studio 2017 上

    python - 将自定义 javascript 添加到 Python 中的 FastAPI Swagger UI 文档网页