I have a simple model like:
public class Employer
{
[Required(ErrorMessage = "Please specify id")]
public int Id { get; set; }
[MaxLength(256, ErrorMessage = "Max lenght should be less than 256")]
[Required(ErrorMessage = "Please specify Name")]
public string Name { get; set; }
[Required(ErrorMessage = "Please specify id of organization")]
public int OrganizationId { get; set; }
}
then controller is:
public IHttpActionResult Post(Employer employer)
{
if(!IsActiveOrganization(employer.OrganizationId))
{
ModelState.AddModelError(nameof(employer.OrganizationId), "The organization is not active!");
}
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
}
As you can see I'm trying to validate model before creating a new employer. So, when I pass model with invalid id
then response will like:
{
"message": "The request is invalid.",
"modelState": {
"employer.Id": [
"Please specify id."
]
}
}
I want to check if OrganizationId
is active. For that I have a method IsActiveOrganization
it checks and returns true/false
. If false
then I need to add model error and return 400 Bad Request to client. Everything works but in way that I implemented I will get response like:
{
"message": "The request is invalid.",
"modelState": {
"employer.Id": [
"Please specify id"
],
"OrganizationId": [
"The organization is not active!"
]
}
}
How can I add prefix to ModelState error key like employer.Id
for my own error OrganizationId
? Should I have hardcode employer.OrganizationId
or there is any better way? Please let me know if I need to add mode details. Thanks.