yuanrui / blog

Some notes.
http://yuanrui.github.io
3 stars 0 forks source link

Asp.Net Core中禁用模型的隐式Required验证 #53

Open yuanrui opened 1 year ago

yuanrui commented 1 year ago

一个.net core 2.1的项目升级到.net 6,post请求时出现“The XXX field is required.”的验证错误。

{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "00-36e71dbf52b567b263bc21218b44c679-754419d31dc03116-00",
  "errors": {
    "Id": [
      "The Id field is required."
    ],
    "Name": [
      "The Name field is required."
    ],    
    "RequestUrl": [
      "The RequestUrl field is required."
    ],
    "Description": [
      "The Description field is required."
    ]
  }
}

造成这个异常的主要原因是MVC启用了隐式非空属性验证,当字段属于非空类型时,自动启用Required特性验证。模型绑定时当检测到字段值为空时,验证会出现字段是必须的错误。 一种解决的办法是将模型的属性设置成可为空的类型。

public class DemoViewModel
{
        public string? Id { get; set; }

        public string? Name { get; set; }

        public string? RequestUrl { get; set; }

        public string? Description { get; set; }
}

另一种办法是在Startup设置MvcOptions.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes属性为true,禁用隐式非空属性验证。

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

参考链接:https://learn.microsoft.com/zh-cn/aspnet/core/mvc/models/validation?view=aspnetcore-6.0