You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ModelValidationMiddleware.cs 1.1KB

1234567891011121314151617181920212223242526272829
  1. using Diligent.WebAPI.Contracts.DTOs.Error;
  2. using Microsoft.AspNetCore.Mvc;
  3. using Microsoft.AspNetCore.Mvc.Filters;
  4. namespace Diligent.WebAPI.Host.Middlewares
  5. {
  6. public class ModelValidationMiddleware : IActionFilter
  7. {
  8. public void OnActionExecuted(ActionExecutedContext context) { }
  9. public void OnActionExecuting(ActionExecutingContext context)
  10. {
  11. if (!context.ModelState.IsValid)
  12. {
  13. // create response model
  14. var response = new ErrorResponseDto("Invalid model")
  15. {
  16. // get model validation errors from ModelState
  17. ValidationItems = context.ModelState
  18. .Where(x => x.Value != null && x.Value.Errors.Count > 0)
  19. .Select(x => new ValidationItemDto { Key = x.Key, Value = x.Value?.Errors.Select(e => e.ErrorMessage).First() })
  20. .ToList()
  21. };
  22. // return validation model
  23. context.Result = new BadRequestObjectResult(response);
  24. }
  25. }
  26. }
  27. }