I'm working on a Web API 2 app and I'm implementing request validation. I've included a validation check which looks like this:
if (string.IsNullOrEmpty(userCredentials.UserName))
return BadRequest("UserCredentials.UserName is required");
A 400 response code is returned as expected but the provided message does not appear to be included in the response returned to the client. Am I missing something in the implementation or is there a special way in which I need to process the response received by the client?
UPDATE
The BadRequest message is returned to Postman but when I call it using the C# via a console app I'm not able to find the validation message. Here's the code I'm using in the console app:
static async Task<User> Authenticate(string domain, string userName, string password)
{
using (var client = GetHttpClient())
{
var encoding = Encoding.GetEncoding("iso-8859-1");
var userName64 = Convert.ToBase64String(encoding.GetBytes(userName));
var password64 = Convert.ToBase64String(encoding.GetBytes(password));
var credentials = new { DomainName = domain, UserName = userName64 /*, Password = password64*/ };
var response = await client.PostAsJsonAsync("api/v1/auth", credentials);
var user = await response.Content.ReadAsAsync<User>();
return user;
//return response.Content.ReadAsAsync<User>();
}
}
You are not checking for the bad response. You seem to assume all responses will be 200 as you do not check and just try to parse the response content to your return type.
//...
var response = await client.PostAsJsonAsync("api/v1/auth", credentials);
if(response.IsSuccessStatusCode) { // If 200 OK
//parse response body to desired
var user = await response.Content.ReadAsAsync<User>();
return user;
} else {
//Not 200. You could also consider checking for if status code is 400
var message = await response.Content.ReadAsStringAsync();
//Do something with message like
//throw new Exception(message);
}
//...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With