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

12345678910111213141516171819202122232425262728293031323334
  1. using Diligent.WebAPI.Host.Exceptions;
  2. using Microsoft.AspNetCore.Mvc;
  3. using Microsoft.AspNetCore.Mvc.Filters;
  4. using System.Net;
  5. namespace Diligent.WebAPI.Host.Middlewares
  6. {
  7. public class ModelValidationMiddleware : IActionFilter
  8. {
  9. public void OnActionExecuted(ActionExecutedContext context) { }
  10. public void OnActionExecuting(ActionExecutingContext context)
  11. {
  12. if (!context.ModelState.IsValid)
  13. {
  14. var validationItems = context.ModelState
  15. .Where(x => x.Value != null && x.Value.Errors.Count > 0)
  16. .Select(x => new { Key = x.Key, Value = x.Value?.Errors.Select(e => e.ErrorMessage).First() })
  17. .ToList();
  18. string msg = "";
  19. validationItems.ForEach(n => msg += n.Value + ". ");
  20. var response = new ErrorDetails
  21. {
  22. StatusCode = (int)HttpStatusCode.BadRequest,
  23. Message = msg
  24. };
  25. context.Result = new BadRequestObjectResult(response);
  26. }
  27. }
  28. }
  29. }