Home > Back-end >  Sending a Post Request to register a new user to a Web API, but receiving 400 : BadRequest
Sending a Post Request to register a new user to a Web API, but receiving 400 : BadRequest

Time:05-14

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

CodePudding user response:

Looks like you need to change your test data. I tried to run your data in enter image description here

enter image description here

CodePudding user response:

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.

CodePudding user response:

Change this response.EnsureSuccessStatusCode(); to this

if(response.IsSuccessStatusCode){
         //Code here   
}
  • Related