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

ASP.NET Core模型验证如何返回自定义OperationOutcome格式响应?

ASP.NET Core API 自定义Required验证失败响应格式实现方案

这个需求完全可以实现,无需从头编写完整验证逻辑,利用ASP.NET Core内置的扩展点即可完成自定义响应格式的替换,具体实现方式如下:

1. 定义响应模型类

先创建与目标JSON结构匹配的C#类:

public class OperationOutcome
{
    public string resourceType { get; set; } = "OperationOutcome";
    public List<Issue> issue { get; set; } = new();
}

public class Issue
{
    public string severity { get; set; }
    public string code { get; set; }
    public List<string> location { get; set; } = new();
}

2. 替换默认验证失败响应工厂

在Program.cs中配置Mvc的ApiBehaviorOptions,覆盖默认的InvalidModelStateResponseFactory,将ModelState验证错误转换为目标格式:

builder.Services.AddControllers()
    .ConfigureApiBehaviorOptions(options =>
    {
        options.InvalidModelStateResponseFactory = context =>
        {
            var operationOutcome = new OperationOutcome();

            foreach (var (field, state) in context.ModelState)
            {
                // 生成符合要求的location路径,示例格式为/f:模型名/f:属性名
                // 若需适配多参数场景可扩展逻辑,比如通过参数绑定源识别请求体模型
                var modelName = context.ActionDescriptor.Parameters
                    .First(p => p.BindingInfo?.BindingSource == BindingSource.Body)
                    .ParameterType.Name;
                var location = $"/f:{modelName}/f:{field}";

                foreach (var error in state.Errors)
                {
                    // 识别Required验证失败的场景
                    if (error.ErrorMessage.Contains("required", StringComparison.OrdinalIgnoreCase) ||
                        error.Exception is RequiredAttribute)
                    {
                        operationOutcome.issue.Add(new Issue
                        {
                            severity = "fatal",
                            code = "required",
                            location = new List<string> { location }
                        });
                    }
                }
            }

            return new JsonResult(operationOutcome)
            {
                StatusCode = StatusCodes.Status400BadRequest
            };
        };
    });

3. 效果验证

当带有[Required]注解的模型属性验证失败时,API会直接返回你需要的OperationOutcome格式JSON响应,状态码为400 Bad Request。整个验证流程仍由ASP.NET Core内置机制处理,仅替换了最终的响应输出格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 09:50:25