Search code examples
c#dotnet-httpclient

How to make postAsync to work in Asp.net?


Well, im trying to make a post request to an webapp api. But i keep getting the 400 bad request response. I don't really know what ima doing wrong.

Im trying to make the post to this url http://webapplication1-dev.eba-kqzerfvq.us-east-1.elasticbeanstalk.com/Users with the following code and model.

// Serialize our concrete class into a JSON String
var stringPayload = JsonConvert.SerializeObject(RegistroInput);
var content = new StringContent(stringPayload, Encoding.UTF8, "application/json");
var httpResponse = await client.PostAsync("http://webapplication1-dev.eba-kqzerfvq.us-east-1.elasticbeanstalk.com/Users", content);

RegistroInput is my object which has the parameters to make the post in the url. The model looks like this.

  public class RegistroModel
    {
        public string? email { get; set; }
        public string? username { get; set; }
        public string? password { get; set; }

    }

I honestly feel im introducing the uri wrong or imcomplete, but idk


Solution

  • HTTP 400 means the server is receiving your request but something is wrong with it.

    If you inspect the content of the response, you should get a clue as to what it is that you are doing wrong. I took your URL and submitted an empty structure, then read the contents of the response using:

    //Notice I am short-circuiting the await by reading the Result property for this sample
    var httpResponse = client.PostAsync("http://webapplication1-dev.eba-kqzerfvq.us-east-1.elasticbeanstalk.com/Users", content).Result;
    var responseContent = httpResponse.Content.ReadAsStringAsync().Result;
    

    And these are the contents of responseContent:

    {
        "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
        "title": "One or more validation errors occurred.",
        "status": 400,
        "traceId": "00-006038dec3308d45bf7ada3a0ee1e1c2-96f8ebdb46fc8827-00",
        "errors": {
            "email": [
                "The email field is required."
            ],
            "password": [
                "The password field is required."
            ],
            "username": [
                "The username field is required."
            ]
        }
    }
    

    The server is telling me validation failed. Inspect the error message for the payload you are using and you will find the source of your issue.