.NET 8 Minimal API中如何排除模型属性的表单绑定?
解决表单绑定排除指定属性的问题
针对你遇到的表单绑定会尝试绑定Errors属性导致请求失败的问题,有几种简单有效的解决办法:
方法一:使用[Bind]特性指定允许绑定的属性
直接在模型类上标注[Bind]特性,明确列出需要绑定的属性,模型绑定器会自动忽略未列出的属性,完全避开Errors的绑定问题。
修改后的模型代码:
[Bind("Description,Due")] public class CreateToDoModel { public string Description { get; set; } public string Due { get; set; } public List<FluentValidation.Results.ValidationFailure>? Errors { get; set; } }
这种方法兼容性最好,适配所有.NET版本。
方法二:使用[ExcludeFromBindings]特性(.NET 8+)
如果你使用的是.NET 8或更高版本,可以直接给Errors属性标注[ExcludeFromBindings]特性,这是官方专门为排除模型绑定新增的特性,比[BindNever]更直观有效。
修改后的属性代码:
using Microsoft.AspNetCore.Mvc.ModelBinding; // ... [ExcludeFromBindings] public List<FluentValidation.Results.ValidationFailure>? Errors { get; set; }
方法三:全局配置忽略特定属性
如果需要批量处理多个模型的类似情况,可以在Program.cs中配置模型绑定元数据,指定忽略目标属性:
builder.Services.Configure<MvcOptions>(options => { options.ModelMetadataDetailsProviders.Add( new SuppressBindingMetadataProvider(typeof(CreateToDoModel), nameof(CreateToDoModel.Errors))); });
这种方法适合统一管理多个模型的绑定规则,场景相对特殊。
内容的提问来源于stack exchange,提问作者JensJ
相关产品推荐
相关产品推荐

