Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BadRequest custom error message not returned to client?

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>();
    }
}
like image 913
user9393635 Avatar asked Mar 02 '26 12:03

user9393635


1 Answers

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

//...
like image 70
Nkosi Avatar answered Mar 05 '26 02:03

Nkosi