您可以使用 SchemaNameGenerator 自定义模型名称。您可以参考shadowsheep 的回答。要生成全新的模型名称,您可以将 CustomeAttribute 与 SchemaNameGenerator 一起使用。
public class ClientModelAttribute : Attribute
{
public string Name { get; set; }
public ClientModelAttribute(string name)
{
Name = name;
}
}
internal class CustomSchemaNameGenerator : ISchemaNameGenerator
{
public string Generate(Type type)
{
var attrs = type.GetCustomAttributes(typeof(ClientModelAttribute),true);
foreach (var attr in attrs)
{
if(attr is ClientModelAttribute)
{
ClientModelAttribute clientModel = attr as ClientModelAttribute;
return clientModel.Name;
}
}
return type.FullName;
}
}
具有 CustomAttribute 的模型类
[ClientModel("Foo")]
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public string Summary { get; set; }
}
更新配置服务
services.AddSwaggerDocument(cfg => { cfg.SchemaNameGenerator = new CustomSchemaNameGenerator(); });
招摇.json
"paths": {
"/WeatherForecast": {
"get": {
"tags": [
"WeatherForecast"
],
"operationId": "WeatherForecast_Get",
"responses": {
"200": {
"x-nullable": false,
"description": "",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/Foo"
}
}
}
}
}
}