Swashbuckle.AspNetCore中AdditionalPropertiesAllowed不生效问题
使用Swashbuckle.AspNetCore 6.2.3版本,有一个带[FromBody]参数的POST接口,期望阻止模型接收额外属性。已通过AdditionalPropertiesDocumentFilter在OpenApiSchema上设置AdditionalPropertiesAllowed = false,生成的Schema也包含additionalProperties: false配置,但传入带notAllowedProp等额外属性的请求体时,并未触发预期错误,即使开启了EnableValidator()也无效。
相关配置及测试内容如下:
生成的Schema
"Dto": { "type": "object", "properties": { "attachments": { "type": "array", "items": { "$ref": "#/components/schemas/AttachmentDto" }, "nullable": true }, "items": { "type": "array", "items": { "$ref": "#/components/schemas/EditItemsDto" }, "nullable": true } }, "additionalProperties": false }
测试请求体
{ "attachments": [ { "path": "string", "name": "string", "description": "string", "size": 0 } ], "item": [ { "itemCode": "string", } ], "notAllowedProp" : "test" }
AddSwaggerGen配置
services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Version = "v1", Title = "Service", Description = ApiDocumentation.GetErrorDescriptions() }); var filePath = Path.Combine(AppContext.BaseDirectory, "cm.Service.xml"); c.IncludeXmlComments(filePath); c.AddFluentValidationRules(); c.DocumentFilter<AdditionalPropertiesDocumentFilter>(); });
UseSwaggerUI配置
app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); c.RoutePrefix = string.Empty; c.EnableValidator(); });
1. 核心问题说明
EnableValidator()仅在Swagger UI页面发起请求时做客户端校验,如果直接通过Postman、curl等工具调用接口,这个校验不会生效。真正的额外属性拦截需要通过ASP.NET Core的JSON序列化配置实现,Swagger的Schema配置只是用来生成规范文档,不负责后端逻辑校验。
2. 配置System.Text.Json(默认序列化器)
在AddControllers()中配置JsonOptions,开启禁止未知属性的校验:
builder.Services.AddControllers() .AddJsonOptions(options => { // 关键配置:遇到未知属性时抛出异常 options.JsonSerializerOptions.DisallowUnknownValues = true; // 可选:保持其他序列化配置 options.JsonSerializerOptions.PropertyNameCaseInsensitive = true; options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull; });
配置后,后端接收到包含额外属性的请求时,会抛出JsonException,可以通过全局异常过滤器捕获并返回400 Bad Request响应。
3. 若使用Newtonsoft.Json(Json.NET)
如果项目使用的是Newtonsoft.Json而非默认的System.Text.Json,配置方式如下:
builder.Services.AddControllers() .AddNewtonsoftJson(options => { // 遇到未知属性时抛出异常 options.SerializerSettings.MissingMemberHandling = MissingMemberHandling.Error; });
4. 保留Swagger Schema配置
之前通过AdditionalPropertiesDocumentFilter设置AdditionalPropertiesAllowed = false的操作无需移除,它能正确生成符合要求的OpenAPI文档,让客户端开发者清楚知道接口不接受额外属性。
内容的提问来源于stack exchange,提问作者Denys

