model validation for webapi
Model validation in ASP.NET Core MVC and Razor Pages
webapi:Create web APIs with ASP.NET Core
Automatic HTTP 400 responses
The [ApiController]
attribute makes model validation errors automatically trigger an HTTP 400 response. Consequently, the following code is unnecessary in an action method:
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
ASP.NET Core MVC uses the ModelStateInvalidFilter action filter to do the preceding check.
Default BadRequest response
With a compatibility version of 2.1, the default response type for an HTTP 400 response is SerializableError. The following request body is an example of the serialized type:
{
"": [
"A non-empty request body is required."
]
}
With a compatibility version of 2.2 or later, the default response type for an HTTP 400 response is ValidationProblemDetails. The following request body is an example of the serialized type:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|7fb5e16a-4c8f23bbfc974667.",
"errors": {
"": [
"A non-empty request body is required."
]
}
}
The ValidationProblemDetails
type:
- Provides a machine-readable format for specifying errors in web API responses.
- Complies with the RFC 7807 specification.
Log automatic 400 responses
See How to log automatic 400 responses on model validation errors (aspnet/AspNetCore.Docs #12157).
Customizing automatic HTTP 400 error response in ASP.NET Core Web APIs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | //中间件定义 public class ValidatorActionFilter : IActionFilter { public void OnActionExecuting(ActionExecutingContext filterContext) { if (!filterContext.ModelState.IsValid) { var result = new OAProxyOPResult(); var invalidExceptionContent = ConstructErrorMessages(filterContext.ModelState); var exception = new OAProxyException(Base.OAProxyOpResultCode.ParameterInvalid, JsonConvert.SerializeObject(invalidExceptionContent)); result.Result = exception.ResultCode; result.ResultContent = exception; filterContext.Result = new JsonResult(result); //filterContext.Result = new BadRequestObjectResult(filterContext.ModelState); } } private Dictionary< string , string []> ConstructErrorMessages(ModelStateDictionary modelState) { var errorsResult = new Dictionary< string , string []>(); foreach ( var keyModelStatePair in modelState) { var key = keyModelStatePair.Key; var errors = keyModelStatePair.Value.Errors; if (errors != null && errors.Count > 0) { if (errors.Count == 1) { var errorMessage = GetErrorMessage(errors[0]); errorsResult.Add(key, new [] { errorMessage }); } else { var errorMessages = new string [errors.Count]; for ( var i = 0; i < errors.Count; i++) { errorMessages[i] = GetErrorMessage(errors[i]); } errorsResult.Add(key, errorMessages); } } } return errorsResult; } string GetErrorMessage(ModelError error) { return string .IsNullOrEmpty(error.ErrorMessage) ? "The input was not valid." : error.ErrorMessage; } public void OnActionExecuted(ActionExecutedContext filterContext) { } |
1 2 3 4 5 6 | //startup中添加 services.AddControllers(config => { config.Filters.Add( typeof (ValidatorActionFilter)); }) |
https://stackoverflow.com/questions/49646688/custom-middleware-for-input-validation
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 没有源码,如何修改代码逻辑?
· NetPad:一个.NET开源、跨平台的C#编辑器
· 面试官:你是如何进行SQL调优的?
2016-07-13 三、操作系统知识(3)