ASP.NET Core WEB API 模型验证的有关问题

栏目: ASP.NET · 发布时间: 5年前

内容简介:改变它其中一个作用是

改变 ASP.NET Core WEB API 模型验证的默认行为。

二、问题

ApiControllerAttribure 特性通常结合 ControllerBase 来为控制器启用特定于 REST 行为。 通过 ControllerBase 可使用 NotFoundFile 等方法。

它其中一个作用是 自动 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 可在 ControllerAction 上使用;也可以做一个继承于 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 模型验证的有关问题》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

高可用MySQL

高可用MySQL

)Charles Bell Mats Kindahl Lars Thalmann / 宁青、唐李洋 诸云萍 / 电子工业出版社 / 2011-10 / 98.00元

《高可用mysql:构建健壮的数据中心》是“mysql high availability”的中文翻译版,主要讲解真实环境下如何使用mysql 的复制、集群和监控特性,揭示mysql 可靠性和高可用性的方方面面。本书由mysql 开发团队亲自执笔,定位于解决mysql 数据库的常见应用瓶颈,在保持mysql 的持续可用性的前提下,挖潜各种提高性能的解决方案。本书分为三个部分。第一部分讲述mysql......一起来看看 《高可用MySQL》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具