如何生成Scheme的Example

提问

如何生成Scheme的Example

回答

  1. 引入
Swashbuckle.AspNetCore.Annotations
  1. 服务注入
builder.Services.AddSwaggerGen(options => {
    options.EnableAnnotations();
});
  1. 编写实体的过滤器
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Annotations;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace OpenAPI2MD.CommunityToolkit.Example
{
    /// <summary>
    /// 天气信息实体
    /// </summary>
    [SwaggerSchemaFilter(typeof(WeatherForecastilter))]
    public class WeatherForecast
    {
        /// <summary>
        /// 日期
        /// </summary>
        /// <example>
        /// 2022-01-01
        /// </example>
        /// <value>2022-01-01</value>
        [SwaggerSchema("订单号", ReadOnly = true)]
        public DateTime Date { get; set; }
        /// <summary>
        /// 温度
        /// </summary>
        public int TemperatureC { get; set; }

        public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
        /// <summary>
        /// 汇总
        /// </summary>
        /// <example>
        /// 汇总是这样子的
        /// </example>
        /// <value>asdfasdf</value>
        public string? Summary { get; set; }
    }
    public class WeatherForecastilter : ISchemaFilter
    {
        public void Apply(OpenApiSchema schema, SchemaFilterContext context)
        {
            schema.Example = new OpenApiObject
            {
                ["Date"] = new OpenApiDate(DateTime.Now),
                ["Summary"] = new OpenApiString("汇总是这样子的")
            };
        }
    }
}
  1. example
posted @ 2022-10-11 13:45  喜爱糖葫芦  阅读(94)  评论(0编辑  收藏  举报