Hi @Amir Shaikh ,
You could try to create a Custom validation Error model, and then use the action filter to handle the Validation failure error response. Check the following sample code:
- Create custom ValidationError model which contains the returned fields:
public class ValidationError { [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public string Field { get; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public int Code { get; set; } public string Message { get; } public ValidationError(string field,int code, string message) { Field = field != string.Empty ? field : null; Code = code != 0 ? code : 55; //set the default code to 55. you can remove it or change it to 400. Message = message; } } public class ValidationResultModel { public string Message { get; } public List<ValidationError> Errors { get; } public ValidationResultModel(ModelStateDictionary modelState) { Message = "Validation Failed"; Errors = modelState.Keys .SelectMany(key => modelState[key].Errors.Select(x => new ValidationError(key,0, x.ErrorMessage))) .ToList(); } }
- Create custom IActionResult. By default, when display the validation error, it will return BadRequestObjectResult and the HTTP status code is 400. Here we could change the Http Status code.
public class ValidationFailedResult : ObjectResult { public ValidationFailedResult(ModelStateDictionary modelState) : base(new ValidationResultModel(modelState)) { StatusCode = StatusCodes.Status422UnprocessableEntity; //change the http status code to 422. } }
- Create Custom Action Filter attribute:
public class ValidateModelAttribute: ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext context) { if (!context.ModelState.IsValid) { context.Result = new ValidationFailedResult(context.ModelState); } } }
- Change the default response type to SerializableError in Startup.ConfigureServices:
services.AddControllers().ConfigureApiBehaviorOptions(options => { options.InvalidModelStateResponseFactory = context => { var result = new ValidationFailedResult(context.ModelState); // TODO: add `using System.Net.Mime;` to resolve MediaTypeNames result.ContentTypes.Add(MediaTypeNames.Application.Json); return result; }; });
- Add the custom action filter at the action method or controller.
[HttpPost] [ValidateModel] public async Task<ActionResult<Student>> PostStudent(Student student) { ... }
- Create a Student model :
public class Student { [Key] public int Id { get; set; } [Required(ErrorMessage = "Please enter Firstname")] public string Firstname { get; set; } [Required(ErrorMessage = "Please enter Lastname")] public string Lastname { get; set; } }
Then, if the request body is empty, the result like this:
After get the response, you could deserialize it to the custom ValidationError model.
Reference:
Handle Validation failure errors in ASP.NET Core web APIs
Handling validation responses for ASP.NET Core Web API
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion