Swagger 高级配置与注解使用
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "Test API V1",
Version = "v1",
Description = "A sample API for testing Swashbuckle",
TermsOfService = new Uri("http://tempuri.org/terms")
});
// 启用注解支持,使 Swagger 特性生效
c.EnableAnnotations();
// 全局参数命名转为驼峰格式
c.DescribeAllParametersInCamelCase();
// 多态类型处理:使用 OneOf 模式生成联合类型
c.UseOneOfForPolymorphism();
// 继承关系使用 AllOf 表示
c.UseAllOfForInheritance();
// 自定义鉴别器字段名
c.SelectDiscriminatorNameUsing(baseType => "TypeName");
// 子类型值映射为名称
c.SelectDiscriminatorValueUsing(subType => subType.Name);
// 注入 XML 文档注释
string xmlFileName = Assembly.GetEntryAssembly().GetName().Name + ".xml";
string xmlPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, xmlFileName);
c.IncludeXmlComments(xmlPath, true);
// 定义多态基类的子类型
c.GeneratePolymorphicSchemas(info =>
{
if (info.IsInterface && info.Name == nameof(IAnimal))
{
return new[] { typeof(Cat), typeof(Lion) };
}
return Enumerable.Empty<Type>();
});
// 请求体扩展属性注入
c.RequestBodyFilter<AssignRequestBodyVendorExtensions>();
// 接口操作扩展信息
c.OperationFilter<AssignOperationVendorExtensions>();
// 模型示例数据填充
c.SchemaFilter<ExamplesSchemaFilter>();
});
启用注解功能
引入包:Swashbuckle.AspNetCore.Annotations启用后可使用以下特性: -
[SwaggerRequestBody]:定义请求体描述
- [SwaggerResponse]:指定响应状态码及返回类型
- [SwaggerParameter][SwaggerOperation]:自定义接口摘要与描述
[HttpPost("Product")]
[SwaggerOperation(Summary = "创建订单", Description = "提交新订单信息")]
[SwaggerRequestBody(Description = "订单数据体")]
[SwaggerResponse(200, "创建成功", typeof(Order))]
[SwaggerResponse(400, "请求参数无效")]
public IActionResult Post([FromBody] Order request)
{
return Ok(new { Message = "Success" });
}
[HttpGet("GetOrderName")]
[SwaggerOperation(Summary = "按名称查询订单")]
[SwaggerParameter(Description = "要查询的订单名称", Required = true)]
[ProducesResponseType(typeof(Order), StatusCodes.Status200OK)]
public IActionResult Get([FromQuery] string orderName)
{
var result = new Order { Id = 1, OrderName = "冰箱订单" };
return Ok(result);
}
请求体扩展属性
通过自定义过滤器向请求体添加额外元数据。public class AssignRequestBodyVendorExtensions : IRequestBodyFilter
{
public void Apply(OpenApiRequestBody requestBody, RequestBodyFilterContext context)
{
requestBody.Extensions.Add("x-purpose", new OpenApiString("test111111111"));
}
}
接口级别扩展信息
为每个 API 操作添加自定义扩展字段。public class AssignOperationVendorExtensions : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
operation.Extensions.Add("x-purpose", new OpenApiString("test"));
}
}
模型示例数据填充
在 Schema 中插入预设示例数据。public class ExamplesSchemaFilter : ISchemaFilter
{
public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
schema.Example = GetExampleFor(context.Type);
}
private IOpenApiAny GetExampleFor(Type type)
{
return type.Name switch
{
"Order" => new OpenApiObject
{
["id"] = new OpenApiInteger(123),
["orderName"] = new OpenApiString("冰箱的订单")
},
_ => null
};
}
}
多态类型支持
定义一个接口并注册其子类型,实现动态类型识别。[SwaggerSubType(typeof(Lion))]
[SwaggerSubType(typeof(Cat))]
public interface IAnimal
{
int Id { get; }
string Name { get; }
}
public class Cat : IAnimal
{
public Cat(int id, string name)
{
Id = id;
Name = name;
}
public int Id { get; set; }
public string Name { get; set; }
}
public class Lion : IAnimal
{
public Lion(int id, string name)
{
Id = id;
Name = name;
}
public int Id { get; set; }
public string Name { get; set; }
}
多态接口调用示例
控制器方法根据查询参数返回不同子类型实例。[HttpGet("GetAnimal")]
public ActionResult<IAnimal> GetAnimal([FromQuery] string animalType)
{
return animalType == "lion"
? Ok(new Lion(1, "狮子"))
: Ok(new Cat(2, "猫"));
}