英文:
How to add example responses in Swagger in a ASP .NET minimal API?
问题
I would like to add examples of answers for my endpoints in my minimal API in .NET 7.
我想为我的.NET 7中的最小API添加端点响应示例。
I have already found several interesting resources but none of them work in the context of a minimal API:
- https://www.dotnetnakama.com/blog/enriched-web-api-documentation-using-swagger-openapi-in-asp-dotnet-core/#api-examples-request-and-response
- https://medium.com/@niteshsinghal85/multiple-request-response-examples-for-swagger-ui-in-asp-net-core-864c0bdc6619
我已经找到了一些有趣的资源,但它们都不适用于最小API的情境:
- https://www.dotnetnakama.com/blog/enriched-web-api-documentation-using-swagger-openapi-in-asp-dotnet-core/#api-examples-request-and-response
- https://medium.com/@niteshsinghal85/multiple-request-response-examples-for-swagger-ui-in-asp-net-core-864c0bdc6619
These are the kind of renderings I expect, i.e. a status code, with its description and a specific endpoint (e.g. suppose I have several 400 responses for different cases, I want to be able to differentiate them with a different description and response example).
这是我期望的渲染方式,即状态代码,带有其描述和特定端点(例如,假设我有多个不同情况的400响应,我希望能够使用不同的描述和响应示例来区分它们)。
For example, let imagine that I have the following Startup :
例如,让我们想象我有以下的Startup:
public class Startup
{
public IConfiguration Configuration
{
get;
}
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
/* ... */
// Swagger services
services.AddEndpointsApiExplorer();
services.AddSwaggerGen(BuilderUtils.SwaggerOptions());
/* ... */
}
public void Configure(WebApplication app)
{
// Swagger activation
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
/* ... */
app.MapMyEndpoints();
app.Run();
}
}
With the following method:
使用以下方法:
public static void MapMyEndpoints(this WebApplication app)
{
app.MapGet("/api/foo", () => return await Foo())
.WithOpenApi(op => new(op)
{
OperationId = "MyOperationId",
Tags = new List<OpenApiTag> { new() { Name = "MyTag" } },
Summary = "MySummary",
Description = "MyDescription"
});
app.MapGet("/api/bar", () => return await Bar())
.WithOpenApi(op => new(op)
{
OperationId = "MyOperationId",
Tags = new List<OpenApiTag> { new() { Name = "MyTag" } },
Summary = "MySummary",
Description = "MyDescription"
});
}
Both will respond using the MessageBody class:
两者都将使用MessageBody类进行响应:
public class MessageBody
{
public string? Message { get; set; }
public string? Error { get; set; }
}
For example, Foo will respond either a 200 with the MessageBody:
Message = "Connected",
例如,Foo将使用MessageBody响应200,其中:
Message = "Connected",
or 400 with the MessageBody:
Error = "Wrong Password"
or Error = "Account not found"
或者400响应将使用MessageBody:
Error = "Wrong Password"
或Error = "Account not found"
And it goes on for the other endpoints.
对于其他端点也是如此。
I want to report all of those cases in my Swagger.
我想在我的Swagger中报告所有这些情况。
Because I work using minimal API, I can't use Exemple Filters, or if I can, I don't know how.
因为我使用最小API工作,我不能使用Exemple Filters,或者如果可以的话,我不知道如何使用。
If anyone have a hints on how I can do that I will be really gratefull !
如果有人有关于如何做到这一点的提示,我将非常感激!
英文:
I would like to add examples of answers for my endpoints in my minimal API in .NET 7.
I have already found several interesting resources but none of them work in the context of a minimal API:
- https://www.dotnetnakama.com/blog/enriched-web-api-documentation-using-swagger-openapi-in-asp-dotnet-core/#api-examples-request-and-response
- https://medium.com/@niteshsinghal85/multiple-request-response-examples-for-swagger-ui-in-asp-net-core-864c0bdc6619
These are the kind of renderings I expect, i.e. a status code, with its description and a specific endpoint (e.g. suppose I have several 400 responses for different cases, I want to be able to differentiate them with a different description and response example).
For example, let imagine that I have the following Startup :
public class Startup
{
public IConfiguration Configuration
{
get;
}
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
            /* ... */
// Swagger services
            services.AddEndpointsApiExplorer();
services.AddSwaggerGen(BuilderUtils.SwaggerOptions());            
/* ... */
}
public void Configure(WebApplication app)
{
            // Swagger activation
            if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
/* ... */
app.MapMyEndpoints();
app.Run();
}
}
}
With the following method:
public static void MapMyEndpoints(this WebApplication app)
{
app.MapGet("/api/foo", () => return await Foo())
.WithOpenApi(op => new(op)
{
OperationId = "MyOperationId",
Tags = new List<OpenApiTag> { new() { Name = "MyTag" } },
Summary = "MySummary",
Description = "MyDescription"
});
app.MapGet("/api/bar", () => return await Bar())
.WithOpenApi(op => new(op)
{
OperationId = "MyOperationId",
Tags = new List<OpenApiTag> { new() { Name = "MyTag" } },
Summary = "MySummary",
Description = "MyDescription"
});
}
Both will respond using the MessageBody class :
public class MessageBody
{
public string? Message { get; set; }
public string? Error { get; set; }
}
For example, Foo will respond either a 200 with the MessageBody :
Message = "Connected",
or 400 with the MessageBody :
Error = "Wrong Password"
or Error = "Account not found"
And it goes on for the other endpoints.
I want to report all of those cases in my Swagger.
Because I work using minimal API, I can't use Exemple Filters, or if I can, I don't know how.
If anyone have a hints on how I can do that I will be really gratefull !
答案1
得分: 2
安装 Swashbuckle.AspNetCore.Filters
nuget,然后可以使用相应的属性标记处理程序:
builder.Services.AddSwaggerGen(options => options.ExampleFilters());
builder.Services.AddSwaggerExamplesFromAssemblies(Assembly.GetEntryAssembly());
// ...
app.MapGet("/api/bar",
[SwaggerResponseExample((int)HttpStatusCode.OK, typeof(MessageBodyOkExample))]
[SwaggerResponseExample((int)HttpStatusCode.BadRequest, typeof(MessageBody400Example))]
() => new MessageBody
{
Message = "Connected"
})
.WithOpenApi(op => new(op)
{
// ...
})
.Produces<MessageBody>((int)HttpStatusCode.OK)
.Produces<MessageBody>((int)HttpStatusCode.BadRequest);
和示例响应:
public class MessageBodyOkExample : IExamplesProvider<MessageBody>
{
public MessageBody GetExamples()
{
return new MessageBody()
{
Message = "Connected"
};
}
}
public class MessageBody400Example : IExamplesProvider<MessageBody>
{
public MessageBody GetExamples()
{
return new MessageBody()
{
Error = "testError"
};
}
}
和结果:
英文:
Install the Swashbuckle.AspNetCore.Filters
nuget and then you can mark handlers with corresponding attributes:
builder.Services.AddSwaggerGen(options => options.ExampleFilters());
builder.Services.AddSwaggerExamplesFromAssemblies(Assembly.GetEntryAssembly());
// ...
app.MapGet("/api/bar",
[SwaggerResponseExample((int)HttpStatusCode.OK, typeof(MessageBodyOkExample))]
[SwaggerResponseExample((int)HttpStatusCode.BadRequest, typeof(MessageBody400Example))]
() => new MessageBody
{
Message = "Connected"
})
.WithOpenApi(op => new(op)
{
// ...
})
.Produces<MessageBody>((int)HttpStatusCode.OK)
.Produces<MessageBody>((int)HttpStatusCode.BadRequest);
And sample responses:
public class MessageBodyOkExample : IExamplesProvider<MessageBody>
{
public MessageBody GetExamples()
{
return new MessageBody()
{
Message = "Connected"
};
}
}
public class MessageBody400Example : IExamplesProvider<MessageBody>
{
public MessageBody GetExamples()
{
return new MessageBody()
{
Error = "testError"
};
}
}
And result:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论