如何在ASP.NET Core 7的Swagger中伪造接口输入类型?
问题描述
我有一个基于ASP.NET Core 7和Swashbuckle的项目,现有代码如下:
MyTestClass.cs
/// <summary> /// My Test class /// </summary> /// <param name="MyProperty">My property</param> public record MyTestClass(int MyProperty);
MyController.cs
using Microsoft.AspNetCore.Mvc; namespace WebApplication1.Controllers; [ApiController] [Route("[controller]")] public class MyController : ControllerBase { [HttpPut(Name = "MyPut")] public IActionResult Put(string theInput) { return Ok(); } }
实际Action方法接收string类型参数theInput,但希望Swagger UI显示该接口期望接收MyTestClass类型参数,效果如同方法定义为:
[HttpPut(Name = "MyPut")] public IActionResult Put(MyTestClass myTestClass) { return Ok(); }
需求是构建容错API,若客户端未提交正确格式的数据,可通过其他逻辑处理,需要修改Swagger文档,伪造输入类型为MyTestClass。
解决方案
可以通过自定义Swashbuckle操作过滤器修改Swagger文档的参数元数据,具体实现如下:
1. 创建自定义操作过滤器
实现IOperationFilter接口,精准定位目标Action后,直接替换请求体的Schema为MyTestClass的结构:
using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; using Microsoft.AspNetCore.Mvc.Controllers; using WebApplication1; public class FakeParameterTypeFilter : IOperationFilter { public void Apply(OpenApiOperation operation, OperationFilterContext context) { // 通过ControllerActionDescriptor精准匹配目标Action if (context.ApiDescription.ActionDescriptor is ControllerActionDescriptor actionDesc && actionDesc.ControllerTypeInfo.Name == "MyController" && actionDesc.MethodInfo.Name == "Put") { // 生成MyTestClass对应的Swagger Schema var testClassSchema = context.SchemaGenerator.GenerateSchema(typeof(MyTestClass), context.SchemaRepository); // 替换整个请求体,让Swagger展示MyTestClass的结构 operation.RequestBody = new OpenApiRequestBody { Content = new Dictionary<string, OpenApiMediaType> { ["application/json"] = new OpenApiMediaType { Schema = testClassSchema } } }; } } }
2. 注册过滤器到Swagger配置
在Program.cs的Swagger配置中添加这个自定义过滤器:
builder.Services.AddSwaggerGen(c => { // 保留原有Swagger配置(如文档信息、注释解析等) c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" }); // 添加自定义操作过滤器 c.OperationFilter<FakeParameterTypeFilter>(); });
3. 验证效果
启动项目后,Swagger UI中MyPut接口的请求体将显示为MyTestClass的结构(包含MyProperty字段),但后端实际仍接收string类型的theInput参数,你可以在Action内部自行处理参数的解析、格式校验和容错逻辑。
内容的提问来源于stack exchange,提问作者Adam
相关产品推荐
相关产品推荐

