0

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
}

1 Answer 1

1

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"}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.