'Sending a Post Request to register a new user to a Web API, but receiving 400 : BadRequest
Having issues with my code [ Throwing an Unhandled exception: System.Net.Http.HttpRequestException: Response status code does not indicate success: 400 (Bad Request) ] when trying to connect to WebApi
This is my first time working with await/async methods, but I am needing to return
string msgTask = await response.Content.ReadAsStringAsync(); return msgTask;
At first my Console.WriteLine(await response.Content.ReadAsStringAsync(); returned:
BadRequest {"error":"Password must be at least 8 characters, with at least 1 of each alpha, number and special characters"}
But then I inserted this check: response.EnsureSuccessStatusCode(); which Throws the System.Net.Http.HttpRequestException
Full [top-level styled] Code Below (I am only using Console.WriteLine() to help with debugging, final code will only have return msgTask;) :
HttpRequest.GetHttpResponse();
await WattTime.PostRequest.RegisterUser();
public class HttpRequest
{
public static HttpClient client = new();
public static void GetHttpResponse()
{
// GetRequestMethod to use later
}
}
namespace WattTime
{
class PostRequest : HttpRequest
{
public static async Task<string> RegisterUser()
{
string Url = "https://api2.watttime.org/v2/register";
Dictionary<string, string> parameters = new()
{
{"username", "TestUser" },
{"password", "Password@1" },
{"email", "[email protected]" },
{"org", "XYZ" },
};
var jsonDictionary = JsonConvert.SerializeObject(parameters);
var content = new StringContent(jsonDictionary, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(Url, content);
response.EnsureSuccessStatusCode();
string msgTask = await response.Content.ReadAsStringAsync();
Console.WriteLine(msgTask);
return msgTask;
}
}
}
UPDATE I changed the format of data being sent to the API var data = @"{ ""username"": ""TestUser900"", ""password"": ""Summer$21"", ""email"": ""[email protected]""}";
and added var postData = JsonConvert.SerializeObject(data); var postData2 = JsonConvert.DeserializeObject(postData);
If I use Console.WriteLine(await response.Content.ReadAsStringAsync()) I receive the Status and User Created, but if I use return response.StatusCode.ToString(); nothing returns
Solution 1:[1]
Looks like you need to change your test data. I tried to run your data in Online API testing tool and it returned the same error and later when I changed the json data it returned status 200 OK. Also I observed that every time you need to send unique data or its returning error.
Solution 2:[2]
Your issue may be the @ symbol in your data. If sent in the URL it will need to be URL encoded. See this list of characters that need encoding https://www.w3schools.com/tags/ref_urlencode.asp
You can use HttpUtility.UrlEncode to do this on your jsonDictionary variable, HttpServerUtility and WebUtility classes also have this static method.
Solution 3:[3]
Change this response.EnsureSuccessStatusCode(); to this
if(response.IsSuccessStatusCode){
//Code here
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Srikanth Kotnala |
| Solution 2 | Philip Smith |
| Solution 3 | Cyrille Con Morales |


