Hello I am trying to get custom validation response for my webApi using .NET Core.
Here I want to have response model like
[{
ErrorCode:
ErrorFi
As for me, it's better to use the following code in ASP.NET Core project
services.AddMvc().ConfigureApiBehaviorOptions(options =>
{
options.InvalidModelStateResponseFactory = c =>
{
var errors = string.Join('\n', c.ModelState.Values.Where(v => v.Errors.Count > 0)
.SelectMany(v => v.Errors)
.Select(v => v.ErrorMessage));
return new BadRequestObjectResult(new
{
ErrorCode = "Your validation error code",
Message = errors
});
};
});
Also take into account that instead of anonymous object you can use your concrete type. For example,
new BadRequestObjectResult(new ValidationErrorViewModel
{
ErrorCode = "Your validation error code",
Message = errors
});