Search code examples
c#validationasp.net-web-apimodelstate

How to return another type instead of ModelStateDictionary when we check modelstate in web api?


We have something by the name Modelstate which return a ModelStateDictionary What I figured out we can put some attributes on our model properties and check ModelState.IsValid and If something is required and is null when we return model state it shows the error, what I want is want to use that attributes and check ModelState.IsValid but I want to return my return type format

my input to api is :

public class Input
{
    [Required]
    public string Name { get; set; }
    [Required]
    [Range(500, 50000)]
    public int AccountBalance{ get; set; }
}

my api output is like:

public  class Output
{
    public string ErrorDetail { get; set; }
    public int ErrorCode { get; set; }
}

in my controller I want to check validation

       if (!ModelState.IsValid)
        {

     //based on which property has problem I want to decide about the return 
      //error code
        return new Output
                {
                    Description = "error about name",
                    ErrorCode = "1020"
                }

            }

Is there any way to do this in a clean way?


Solution

  • Just use the the Content<T> method of ApiController:

    if (!ModelState.IsValid)
    {
        return Content(HttpStatusCode.BadRequest, new Output
        {
            ErrorDetail = "error about name",
            ErrorCode = "1020"
        });
    }
    

    It negotiates the content and returns the provided HTTP status code.

    Note that 400 BadRequest is the usual HTTP error status code used when there is an invalid request (e.g. validation fails).