gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 17:20:16 34 4
gpt4 key购买 nike

我使用的是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/

    34 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com