内容简介:改变它其中一个作用是
改变 ASP.NET Core WEB API
模型验证的默认行为。
二、问题
ApiControllerAttribure
特性通常结合 ControllerBase
来为控制器启用特定于 REST
行为。 通过 ControllerBase
可使用 NotFound
和 File
等方法。
它其中一个作用是 自动 HTTP 400 响应
。即验证错误会自动触发 HTTP 400
响应。 操作中不需要以下代码:
if (!ModelState.IsValid) { return BadRequest(ModelState); }
如果要改变这种行为,比如希望以 HTTP 200
响应,则有如下解决方案 。
三、解决方案
1、第一步
当 SuppressModelStateInvalidFilter
属性设置为 true
时,会禁用默认行为。 将以下代码添加至 Startup.ConfigureServices
中的 services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
; 后:
// File: Startup.cs Method: ConfigureServices services.Configure<ApiBehaviorOptions>(options => { options.SuppressModelStateInvalidFilter = true; });
2、解决方案1: 在 Action 开头进行验证
// File: XXXController.cs Method: XXXAction if (!ModelState.IsValid) { return new OkObjectResult(ModelState); }
3 、解决方案2:自定义 ActionFilterAttribure
// File: ModelValidaionActionFilterAttribute.cs public class ModelValidaionActionFilterAttribute : ActionFilterAttribure { public override void OnActionExecuting(ActionExecutingContext context) { if (!context.ModelState.IsValid) { context.Result = new OkObjectResult(context.ModelState); } else { base.OnActionExecuting(context); } } }
ModelValidaionActionFilterAttribute
可在 Controller
或 Action
上使用;也可以做一个继承于 ControllerBase
的类,在其上使用该 Attribute
,而其他 Controller
继承与该类;也可以全局注册 ModelValidaionActionFilterAttribute
:
// File: Startup.cs Method: ConfigureServicess services.AddMvc(options => { options.Filters.Add(typeof(ModelValidaionActionFilterAttribute)); }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
4、解决方案3:使用 InvalidModelStateResponseFactory
不用再将 SuppressModelStateInvalidFilter
设置为 true
,不再使用 ModelValidaionActionFilterAttribute
, 也无需在 Action
中判断 ModelState.IsValid
。
// File: Startup.cs Method: ConfigureServices services.Configure<ApiBehaviorOptions>(options => { options.InvalidModelStateResponseFactory = context => new OkObjectResult(context.ModelState); });
四、其他
不太重要的优化。模型验证时如果发生错误,将继续验证字段,直至达到错误数上限(默认为 200
个)。 通过向 Startup.cs
文件中的 ConfigureServices
方法插入以下代码,可配置该数字:
// File: Startup.cs Method: ConfigureServicess services.AddMvc(options => { options.MaxModelValidationErrors = 1; }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
以上所述就是小编给大家介绍的《ASP.NET Core WEB API 模型验证的有关问题》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- [深度学习] 使用Darknet YOLO 模型破解中文验证码点击识别
- C# 工具包 Newbe.ObjectVisitor 0.4.4 发布,模型验证器上线
- 表单正则验证及文件上传验证功能
- angular 实现同步验证器跨字段验证
- Spring Security验证流程剖析及自定义验证方法
- TensorFlow 推出数据验证函数库 TFDV,用于分析和验证
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。