You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core Web API如何自定义请求体字段类型错误提示信息?

解决ASP.NET Core Web API自定义类型不匹配错误提示的方法

1. 自定义模型验证错误响应(替换默认ApiBehaviorOptions)

在Program.cs(.NET 6+)或Startup.cs(旧版本)中配置ApiBehaviorOptions,重写默认的错误响应生成逻辑,过滤内部变量名并生成友好提示:

builder.Services.Configure<ApiBehaviorOptions>(options =>
{
    options.InvalidModelStateResponseFactory = context =>
    {
        var errorDict = new Dictionary<string, string[]>();

        foreach (var key in context.ModelState.Keys)
        {
            var errorList = context.ModelState[key].Errors
                .Select(err =>
                {
                    // 识别JSON类型转换错误,生成友好提示
                    if (err.ErrorMessage.Contains("could not be converted to System.String"))
                    {
                        var fieldName = key.Replace("$.", "");
                        return $"字段 {fieldName} 必须为字符串格式";
                    }
                    // 保留自定义验证错误信息,无信息时返回通用提示
                    return string.IsNullOrEmpty(err.ErrorMessage) ? "字段格式无效" : err.ErrorMessage;
                })
                .ToArray();

            // 跳过内部参数名(如registerData)的错误条目
            if (!key.Equals("registerData", StringComparison.OrdinalIgnoreCase))
            {
                var cleanFieldName = key.Replace("$.", "");
                errorDict[cleanFieldName] = errorList;
            }
        }

        var problemDetails = new ProblemDetails
        {
            Status = StatusCodes.Status400BadRequest,
            Title = "请求参数验证失败",
            Errors = errorDict
        };

        return new BadRequestObjectResult(problemDetails);
    };
});

2. 捕获底层JSON反序列化错误

若部分类型不匹配错误未进入ModelState,可通过自定义中间件捕获JsonException:

步骤1:创建中间件类

public class JsonErrorHandlingMiddleware
{
    private readonly RequestDelegate _next;

    public JsonErrorHandlingMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (JsonException ex)
        {
            context.Response.StatusCode = StatusCodes.Status400BadRequest;
            context.Response.ContentType = "application/json";

            var fieldName = ex.Path.ToString().Replace("$.", "");
            var friendlyMsg = $"字段 {fieldName} 格式不正确,请输入合法的字符串";

            var problemDetails = new ProblemDetails
            {
                Status = StatusCodes.Status400BadRequest,
                Title = "请求参数格式错误",
                Errors = new Dictionary<string, string[]>
                {
                    { fieldName, new[] { friendlyMsg } }
                }
            };

            await context.Response.WriteAsJsonAsync(problemDetails);
        }
    }
}

步骤2:注册中间件

在Program.cs的管道中添加该中间件(需放在UseRouting之前):

app.UseMiddleware<JsonErrorHandlingMiddleware>();
app.UseRouting();
// 其他中间件注册...

3. 最终效果示例

配置完成后,传入类型不匹配的参数时,会返回简洁友好的响应:

{
  "title": "请求参数验证失败",
  "status": 400,
  "errors": {
    "lastName": [
      "字段 lastName 必须为字符串格式"
    ]
  }
}

补充优化

  • 可根据业务需求修改错误文案,比如将“字段 lastName 必须为字符串格式”改为“姓氏需输入文本内容”;
  • 若需处理更多类型转换错误(如日期格式、数字格式),可扩展错误判断逻辑,生成对应场景的提示语。

内容的提问来源于stack exchange,提问作者iKingNinja

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 06:47:17