ASP Net Core Web API自定义模型验证

阿肖克

ASP Net Core Web API,我正在尝试为模型验证器返回自定义响应。但是,当必填字段不在请求中时,不会调用ValidateModelFilter。

ValidateModelFilter.cs

public class ValidateModelFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        if (!context.ModelState.IsValid)
        {
             var response = new Model
             {
                 error = context.ModelState.ToString()
             };
             context.Result = new BadRequestObjectResult(response);
         }
    }
}

启动文件

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc(options => options.Filters.Add(typeof(ValidateModelFilter)));
}

我得到这样的回应

{
  "errors": {
    "Firstname": [
      "The Firstname field is required."
    ]
  },
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "|e6752549-4142e91f1074e978."
}

我想返回一个像

{
"error": "The Firstname field is required."
}
大卫·希尔斯·夏普

该链接显示了我们如何禁用默认的Model Binding Exception过滤器,该过滤器返回400错误并使管道短路。只有这样,我们的自定义ActionFilterAttribute中的OnActionExecuting方法才真正被执行。然后一切都会按预期进行。

https://stackoverflow.com/a/51522487/14924779

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

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

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

ASP.NET Core Web API中用于整数值的自定义模型验证器

自定义身份验证ASP.NET Core Web API

ASP.NET Core-自定义模型验证

如何在ASP.NET Core中实现自定义模型验证?

关于模型验证ASP.NET Core MVC的自定义错误消息

ASP.NET Core自定义验证创建模型的新实例

ASP.NET Core 3.1 Web API - 自定义 json

ASP.Net Core Web API自定义路由不起作用

ASP.NET Core处理Web API中的自定义响应/输出格式的方法

如何在Swashbuckl ASP.NET Core Web API上添加自定义标头

Asp.net Core 2.1 Web API中的自定义授权

ASP.NET CORE:自定义验证

ASP.Net Core API 将模型 int Id 绑定到自定义 Id 对象

400错误的请求| 从ASP.NET Web API接收自定义错误消息或模型

在.NET Core Web API中使用自定义属性进行JWT身份验证

具有自定义身份验证的ASP.NET Web API

带有OWIN的ASP.NET Web Api-自定义身份验证

ASP.Net Core v3.1 MVC ajax表单中的自定义模型验证似乎无法正常工作

带有自定义响应包装器的 ASP.NET Core 3.1 Web API 中的 JSON 响应中断

如何将自定义标头添加到ASP.NET Core Web API响应

是否可以将路由值绑定到ASP.NET Core Web API中的自定义属性的属性?

在 ASP.net core web api (Swashbuckle.AspNetCore -- Version="5.0.0-rc4") 中添加自定义标题

调试asp.net core web API

Asp.net Core Api 自定义路由

JSON响应自定义.NET Core Web API

我需要在ASP.Net核心Web API的验证属性中返回自定义的验证结果(响应)

创建 swagger 示例模型 asp.net core web api

如何在ASP.NET Core Web API中的每种方法中进行模型验证?

ASP.NET Core Web API验证错误处理