How to create the API error response format same like the default format?

Viewed 28

For example, in my C# model, I have

public class Account
{
    public int Id { get; set; }
    public AccountType AccountType { get; set; }
    public string Name { get; set; }     
}

Note: AccountType is C# enum

When I test it using Postman with POST request like below,

{
    "AccountType": "a",    
    "Name": "John"
}

The error response is 400 Bad Request

{
    "accountType": [
        "Error converting value \"a\" to type 'Models.App.Enum.AccountType'. Path 'AccountType', line 2, position 22."
    ]
}

Now, I have manual validation for Name property.

if (string.IsNullOrEmpty(account.Name))
{
    return BadRequest("Name is required");
}

But when I test it using Postman with POST request like below, { "AccountType": "1",
"Name": "" }

The error response is 400 Bad Request

Name is required

My question is how to I manually write my Name validation so that the error response format will be like similar format like AccountType? This is so that front end developer can get the error message from standardized error response format. or should I manually write validation for AccountType to match with Name format?

1 Answers

You can create anonymous object and pass that object as result.

return BadRequest(new { Name = new string[] {"Name is Required"} });
Related