Razort4x
Razort4x

Reputation: 3406

How to return error message from MVC Web API that returns a Model?

I have this method

[HttpPost]
public ContactModel Contact() 
{
// validation contact must have at least first name
 if (contactModel.firstName == null)
    return null;                           // This works fine

 /*
 if (contactModel.firstName == null)
    return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Please provide first name");                 // it gives error


// insert to database
}

So, how do I indicate to user to provide at least first name. I thought of adding some header to response, but that is not user friendly.

I also added

if (contactModel.firstName == null) 
{
    Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Please provide first name");          // this doesn't do any good either.
    return null;                           // This works fine
}

Upvotes: 0

Views: 126

Answers (1)

Alaa Masoud
Alaa Masoud

Reputation: 7135

CreateErrorResponse returns a HttpResponseMessage which cannot be cast to ContactModel. You want to throw a HttpResponseException instead and add the error using CreateErrorResponse

throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, 
    "Please provide first name"));

This will return HTTP 400 (Bad Request) with the following json:

{"Message":"Please provide first name"}

Upvotes: 1

Related Questions