I've added fluent validation to a WebApi project which works fine, i get the following JSON response as an example of user registration:
{
"errors": {
"Email": [
"'Email' is not a valid email address."
],
"Password": [
"'Password' must contain at least one uppercase, lowercase, number and symbol"
]
},
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "8000003d-0000-fc00-b63f-84710c7967bb"
}
I'm adding validation if a users email already exists. The format of the error response is very different, i need it the same format to catch the error at the client side.
Error model class:
public class ErrorResponse
{
public List<ErrorModel> Errors { get; set; } = new List<ErrorModel>();
}
public class ErrorModel
{
public string FieldName { get; set; }
public string Message { get; set; }
}
Register controller:
var authResponse = await _identityService.RegisterAsync(request);
if (!authResponse.Success)
{
var errorResponse = new ErrorResponse();
var errorModel = new ErrorModel
{
FieldName = "User",
Message = "A user exists"
};
errorResponse.Errors.Add(errorModel);
return BadRequest(errorResponse);
}
JSON response:
{
"errors": [
{
"fieldName": "User",
"message": "A user exists"
}
]
}
You can use a dictionary for that:
public class ErrorResponse
{
public Dictionary<string,List<string>> Errors { get; set; } = new Dictionary<string,List<string>>();
}
And add values like this :
errorResponse.Add("User",new List<string>{"A user exists"});