是的,ASP.NET Core模型绑定可以通过将ConfigureApiBehaviorOptions
方法添加到Startup.cs
中的ConfigureServices
方法中来配置为报告不必要的JSON属性的错误请求。
以下是一个示例,其中ConfigureApiBehaviorOptions
方法可以被用来配置模型绑定器。在示例中,ConfigureApiBehaviorOptions
方法使用SupressModelStateInvalidFilter
移除了默认的模型状态无效过滤器,然后使用Configure
方法配置模型绑定器,以在绑定模型时报告不必要的JSON属性的错误请求:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers(options =>
{
// Remove the default ModelStateInvalidFilter
options.Filters.Remove(new ModelStateInvalidFilter());
});
services.Configure(options =>
{
options.SuppressModelStateInvalidFilter = true;
options.InvalidModelStateResponseFactory = context =>
{
var problems = new ValidationProblemDetails(context.ModelState);
if (context.ModelState.ErrorCount > 0)
{
problems.Title = "Bad Request";
return new BadRequestObjectResult(problems);
}
return new UnprocessableEntityObjectResult(problems);
};
});
// Other services here
}