【模型验证】未被异常捕获到

问题描述

.Net8
由于新版本

使用 <Nullable>enable</Nullable> 构建

对于这样的字段也是必填

public string Name{get;set;}

处理办法:
1、写为

public string? Name{get;set;}

2、项目属性中禁用null值校验

.csproj文件中
修改为
<Nullable>disable</Nullable>
或者删除这行

3、可以通过在 Program.cs 中配置 SuppressImplicitRequiredAttributeForNonNullableReferenceTypes 来禁用此行为

builder.Services.AddControllers(
    options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);

https://learn.microsoft.com/zh-cn/aspnet/core/mvc/models/validation?view=aspnetcore-8.0#non-nullable-reference-types-and-required-attribute

对于必填的验证可以如上修改

但是如果定义了
public int? Age{get;set;}
但是传参:Age="aaa"
仍然会返回

{
    "errors": {
        "Age ": [
            "Could not convert string to integer: d. Path 'Age', line 2, position 13."
        ],
    },
    "type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "00-914e6cd4bff0a78ce89dc690f5d0a864-8e152639147b3487-00"
}

处理方案

参考:
https://blog.csdn.net/sD7O95O/article/details/118004445
https://www.cnblogs.com/minskiter/p/11601873.html

1.添加过滤器

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace BookApi.Middleware
{
    public class ModelActionFiter : ActionFilterAttribute
    {
        public override void OnActionExecuted(ActionExecutedContext context)
        {
        }

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                var errorResults = new List<ErrorResultDTO>();
                foreach (var item in context.ModelState)
                {
                    var result = new ErrorResultDTO
                    {
                        Field = item.Key,
                    };
                    foreach (var error in item.Value.Errors)
                    {
                        if (!string.IsNullOrEmpty(result.Message))
                        {
                            result.Message += '|';
                        }
                        result.Message += error.ErrorMessage;
                    }
                    errorResults.Add(result);
                }

                context.Result = new OkObjectResult(new
                {
                    Code = StatusCodes.Status400BadRequest,
                    Errors = errorResults
                });
            }
        }
    }

    public class ErrorResultDTO
    {
        public string Field { get; set; }
        public string Message { get; set; }
    }
}

2.关闭默认模型验证过滤器
[ApiController] 默认自带有400模型验证,且优先级比较高,如果需要自定义模型验证,则需要先关闭默认的模型验证
在StartUp.cs 中的MVC服务配置修改
两处改动
(1)添加全局过滤器
options.Filters.Add();
(2)关闭默认的模型验证
o.SuppressModelStateInvalidFilter = true;

            builder.Services.AddControllers(options =>
            {
                options.Filters.Add<ModelActionFiter>();
            }).AddNewtonsoftJson(options =>
                {
                    options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                    options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                }).AddJsonOptions(config =>
                {
                    config.JsonSerializerOptions.PropertyNamingPolicy = null;
                }).ConfigureApiBehaviorOptions(o =>
                {
                    o.SuppressModelStateInvalidFilter = true;
                });
posted @ 2025-04-15 22:58  我有我奥妙  阅读(33)  评论(0)    收藏  举报