为什么 ModelState 返回不同的结果以及如何解决它?

阿尔乔姆G

Asp.net 核心 3.1 WebApi。

我有一个具有所需属性的模型。

1.如果模型无效,则响应包含如下数据:

{
    "errors": {
        "Name": [
            "Update model can't have all properties as null."
        ],
        "Color": [
            "Update model can't have all properties as null."
        ]
    },
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "|f032f1c9-4c36d1e62aa60ead."
}

这对我来说看起来不错。

但是如果我向 modelState.AddModelError("statusId", "Invalid order status id.") 添加一些自定义验证,那么它会返回不同的结构:

[
    {
        "childNodes": null,
        "children": null,
        "key": "statusId",
        "subKey": {
            "buffer": "statusId",
            "offset": 0,
            "length": 8,
            "value": "statusId",
            "hasValue": true
        },
        "isContainerNode": false,
        "rawValue": "11202",
        "attemptedValue": "11202",
        "errors": [
            {
                "exception": null,
                "errorMessage": "Invalid order status id."
            }
        ],
        "validationState": 1
    }
]

看起来 ModelState.IsValid 对控制器来说不再是实际的了,因为错误的请求甚至在它以无效模式进入控制器之前就被返回了。或者是否有一些通过 ModelSate 进行全局验证的标志?

为什么结构不同?怎么弄得一样?在 MVC 中,如何强制访问 api 控制器内部的 ModelState.IsValid 方法?

更新:



    [Route("....")]
    [Authorize]
    [ApiController]
    public class StatusesController : ApiControllerBase
    {


        [HttpPut, Route("{statusId}")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status409Conflict)]
        [Produces("application/json")]
        public async Task<ObjectResult> UpdateStatusAsync(int statusId, [FromBody] StatusUpdateDto orderStatusUpdateDto)
        {

            int companyId = User.Identity.GetClaimValue<int>(ClaimTypes.CompanyId);

            const string errorNotFound  = "There is not order status with this id for such company";
            if (statusId <= 0)
            {
                Logger.LogError(errorNotFound);
                ModelState.AddErrorModel(nameof(statusId), "Invalid order status id")
                throw new NotFound(ModelState);
            }
            
            if (orderStatusUpdateDto == null)
            {
                const string error = "Invalid (null) order status can't be added";
                Logger.LogError(error);
                throw new ArgumentNullException(error);
            }

            if (ModelState.IsValid == false) // also this code is always true or returns 400 before this line
            {
                return BadRequest(ModelState); 
            }

           ....
            return result;
        }

}
十三

ApiController属性向控制器添加了一些特定的自以为是的行为。其中之一是如果模型无效则返回 400 错误。可以禁用此行为,但仅限于全局级别。

services.AddControllers()
    .ConfigureApiBehaviorOptions(options =>
    {
        options.SuppressModelStateInvalidFilter = true;
    });

我认为您有以下选择:

  • 禁用此行为并检查ModelState.IsValid自己。使用ValidationProblem方法产生相同的响应
  • 将此检查添加到模型的验证器
  • 保持一切原样。但是ValidationProblem在控制器方法内部使用以返回验证错误。

有关信息,请参阅https://docs.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-3.1#automatic-http-400-responses

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

为什么ModelState.IsValid总是返回true?

ffmpeg - avcodec_receive_frame 返回-11,为什么以及如何解决它?

phpmyadmin受阻,为什么以及如何解决它?

为什么我的代码会死锁以及如何解决它

谁能告诉我为什么对对象Staff使用Null以及如何解决它

Promise 中的 setTimeout - 如何解决以及为什么它只运行一次?

为什么我的列表成为整数,以及如何解决它

ASP.NET MVC Core 3.0-为什么来自正文的API请求始终返回!ModelState.IsValid?

MissingManifestResourceException是什么意思,以及如何解决它?

为什么QXmlQuery似乎在结果中添加了一个\ n?(以及如何解决?)

在代码的最后一行中,我尝试进行投射,但返回null。我的意思是选择=空。我想知道为什么以及如何解决它

为什么返回值不确定?以及如何解决?

为什么fmax(a,b)返回较小的(负)零,以及如何彻底解决它?

ModelState.IsValid为true,但是为什么呢?

为什么MVC在GET上提供的模型上使用Modelstate

为什么 [Required] 属性不会导致 modelState 中的错误

ModelState.Isvalid,为什么要验证相关表?

为什么hwclock和date显示不同的结果以及如何更正它

为什么用settimeout未定义ajax值返回?我如何解决它?

为什么它不旋转呢?以及如何解决?

JavaFX为什么会模糊控件,以及如何解决?

无法注册硬盘VBox。为什么以及如何解决?

为什么pygame滞后以及如何解决?

在MySQL中,“开销”是什么意思,它的缺点是什么,以及如何解决它?

为什么Break会让我一次跳出2个循环,以及如何解决它

为什么Vim与Ctrl + v一起使用时会吞噬Ctrl,以及如何解决它?

为什么我会收到“类型测试的重复修饰符”以及如何解决它

我的脚本出现语法错误,但我不知道为什么以及如何解决它>

为什么函数返回 undefined 以及如何调试它?