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.

47 lines
2.2 KiB

  1. using Common.Models.ModelValidation;
  2. using Common.Models.RequestResponse;
  3. using log4net;
  4. using Newtonsoft.Json;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Net.Http;
  9. using System.Web.Http.Controllers;
  10. using System.Web.Http.Filters;
  11. namespace ThirdPartyAPIs.CustomFilter
  12. {
  13. public class ValidationActionFilter : ActionFilterAttribute
  14. {
  15. private readonly ILog _log = LogManager.GetLogger(typeof(ValidationActionFilter));
  16. public override void OnActionExecuting(HttpActionContext actionContext)
  17. {
  18. var modelState = actionContext.ModelState;
  19. if (!modelState.IsValid)
  20. {
  21. TPResponse jsonResponse = new TPResponse();
  22. jsonResponse.ResponseCode = "104";
  23. jsonResponse.Msg = "Model Not Valid";
  24. List<FieldsValidation> modelList = new List<FieldsValidation>();
  25. foreach (var item in modelState.Keys)
  26. {
  27. var err = modelState[item].Errors.ToList();
  28. err.Select(x =>
  29. {
  30. var mes = (string.IsNullOrWhiteSpace(x.ErrorMessage) && string.IsNullOrEmpty(x.ErrorMessage) ? (!string.IsNullOrEmpty(x.Exception.Message) && !string.IsNullOrWhiteSpace(x.Exception.Message) ? x.Exception.Message : "") : x.ErrorMessage);
  31. modelList.Add(new FieldsValidation() { Name = item.Split('.')[1], Message = mes });
  32. return x;
  33. }).ToList();
  34. }
  35. jsonResponse.Data = modelList;
  36. var a = JsonConvert.SerializeObject(jsonResponse);
  37. //var abc = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, jsonResponse);
  38. //actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, jsonResponse);
  39. //actionContext.Response = actionContext.Request
  40. // .CreateErrorResponse(HttpStatusCode.BadRequest, a.ToString());
  41. _log.Info("Fields Are Not Valid Data:" + a);
  42. actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, a.ToString());
  43. }
  44. }
  45. }
  46. }