| 1234567891011121314151617181920212223242526272829 |
- using Diligent.WebAPI.Contracts.DTOs.Error;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.AspNetCore.Mvc.Filters;
-
- namespace Diligent.WebAPI.Host.Middlewares
- {
- public class ModelValidationMiddleware : IActionFilter
- {
- public void OnActionExecuted(ActionExecutedContext context) { }
-
- public void OnActionExecuting(ActionExecutingContext context)
- {
- if (!context.ModelState.IsValid)
- {
- // create response model
- var response = new ErrorResponseDto("Invalid model")
- {
- // get model validation errors from ModelState
- ValidationItems = context.ModelState
- .Where(x => x.Value != null && x.Value.Errors.Count > 0)
- .Select(x => new ValidationItemDto { Key = x.Key, Value = x.Value?.Errors.Select(e => e.ErrorMessage).First() })
- .ToList()
- };
- // return validation model
- context.Result = new BadRequestObjectResult(response);
- }
- }
- }
- }
|