3

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>();
    }
}
user9393635
  • 1,369
  • 4
  • 13
  • 32

2 Answers2

5

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);
}

//...
Nkosi
  • 235,767
  • 35
  • 427
  • 472
0
using(var response = await client.PostAsJsonAsync("api/v1/auth", credentials)){
    if(response.IsSuccessStatusCode) { 
        //This Code is Executed in Case of Success
        var user = await response.Content.ReadAsAsync<User>();
        return user;
    } 
    else {
        //This Code is Executed in Case of In Case of Other Than Success
        var message = await response.Content.ReadAsStringAsync();
    }
}

You Can use this refactored code, If you want to catch the error message in case of bad request or NotFound etc.