Добавьте собственный сериализатор в Swagger в моем. Net основном API - PullRequest
2 голосов
/ 24 января 2020

Я использую JSONAPI спецификации от jsonapi.org , затем я использую JsonApiSerializer для выполнения sh спецификации 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"
}

Я думаю, что Swagger игнорирует JsonApiSerializer , есть ли способ изменить сериализатор по умолчанию для swagger и использовать мой собственный сериализатор?

Мой 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();
            });
        }
    }
  • Net core 3.1
  • Swashbuckle.AspNetCore 5.0.0
...