.NET 7 Minimal API中如何为Swagger添加响应示例?
.NET 7 Minimal API 为接口添加多场景Swagger响应示例
需求说明
需要在.NET 7 Minimal API的Swagger文档中,为接口端点展示不同状态码的响应场景,包括状态码、描述及对应响应示例。以/api/foo为例:
- 200状态码:返回
MessageBody对象,Message字段为"Connected" - 400状态码:两种场景,分别返回
Error字段为"Wrong Password"或"Account not found"的MessageBody对象
解决方案
1. 创建响应示例扩展方法
实现一个扩展方法,简化为OpenApiResponse添加示例的操作:
using Microsoft.OpenApi.Models; using System.Text.Json; public static class OpenApiResponseExtensions { public static OpenApiResponse WithExample<T>(this OpenApiResponse response, T example) { var schema = new OpenApiSchema(); var jsonContent = JsonSerializer.Serialize(example); schema.Example = OpenApiAnyFactory.CreateFromJson(jsonContent); // 确保application/json内容类型存在 if (!response.Content.ContainsKey("application/json")) { response.Content.Add("application/json", new OpenApiMediaType { Schema = schema }); } else { response.Content["application/json"].Schema = schema; } return response; } }
2. 为端点配置多场景响应示例
在端点映射的WithOpenApi回调中,直接修改OpenApiOperation的Responses集合,添加不同状态码的响应场景:
public static void MapMyEndpoints(this WebApplication app) { app.MapGet("/api/foo", async () => { // 示例业务逻辑,实际替换为真实代码 var random = new Random(); var status = random.Next(3); return status switch { 0 => Results.Ok(new MessageBody { Message = "Connected" }), 1 => Results.BadRequest(new MessageBody { Error = "Wrong Password" }), 2 => Results.BadRequest(new MessageBody { Error = "Account not found" }), _ => Results.StatusCode(500) }; }) .WithOpenApi(op => { op.OperationId = "Foo_Get"; op.Tags = new List<OpenApiTag> { new() { Name = "MyTag" } }; op.Summary = "获取Foo连接状态"; op.Description = "返回连接成功信息或错误提示"; // 配置200成功响应 op.Responses["200"].Description = "连接成功"; op.Responses["200"].WithExample(new MessageBody { Message = "Connected" }); // 配置400场景1:密码错误 var badRequestWrongPwd = new OpenApiResponse { Description = "输入的密码不正确" }.WithExample(new MessageBody { Error = "Wrong Password" }); op.Responses.Add("400-WrongPassword", badRequestWrongPwd); // 配置400场景2:账号不存在 var badRequestAccountNotFound = new OpenApiResponse { Description = "未找到指定账号" }.WithExample(new MessageBody { Error = "Account not found" }); op.Responses.Add("400-AccountNotFound", badRequestAccountNotFound); return op; }); // /api/bar端点可参照上述方式配置 app.MapGet("/api/bar", async () => { return Results.Ok(new MessageBody { Message = "Bar资源获取成功" }); }) .WithOpenApi(op => { op.OperationId = "Bar_Get"; op.Tags = new List<OpenApiTag> { new() { Name = "MyTag" } }; op.Summary = "获取Bar资源"; op.Description = "返回Bar资源数据"; op.Responses["200"].Description = "获取成功"; op.Responses["200"].WithExample(new MessageBody { Message = "Bar资源获取成功" }); return op; }); }
3. 保持Startup配置不变
原有的Startup配置无需修改,确保Swagger服务和中间件已正确注册:
public class Startup { public IConfiguration Configuration { get; } public Startup(IConfiguration configuration) { Configuration = configuration; } public void ConfigureServices(IServiceCollection services) { /* 其他服务配置 */ services.AddEndpointsApiExplorer(); services.AddSwaggerGen(BuilderUtils.SwaggerOptions()); /* 其他服务配置 */ } public void Configure(WebApplication app) { if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } /* 其他中间件配置 */ app.MapMyEndpoints(); app.Run(); } }
效果说明
启动项目后,在Swagger UI中打开/api/foo端点,会看到:
- 200响应:描述为"连接成功",示例JSON为
{"Message":"Connected","Error":null} - 400-WrongPassword响应:描述为"输入的密码不正确",示例JSON为
{"Message":null,"Error":"Wrong Password"} - 400-AccountNotFound响应:描述为"未找到指定账号",示例JSON为
{"Message":null,"Error":"Account not found"}
内容的提问来源于stack exchange,提问作者heexos
相关产品推荐
相关产品推荐

