Search code examples
c#javascriptserializer

C# json POST request 400 error


Trying to get a json post request to work. The error seems to be with the request body as per the error response. Cant seem to figure out the reason. If i post the same request body string through POSTMAN, i get a success response.

var bodyData = new
{
id = "1234567",
eventType = "create",
userId = "account-70540"
}
var js = new JavaScriptSerializer();
string reqBody = js.Serialize(bodyData);

In the section where the request is processed:

HttpWebRequest request = WebRequest.Create(reqUrl) as HttpWebRequest;
request.Method = "POST";                
request.ContentType = "application/json";
request.Headers.Set("x-tracking-id", "12345");
HttpWebResponse response = request.GetResponse() as HttpWebResponse;

The last line triggers the exception and i get a 400 Bad request.Unexpected error while decoding json: Message entity must not be empty.

If i copy the string reqBody and use it as a body in Postman, it works. Could you help with what i'm missing please.


Solution

  • You can try something like this:

    public static string PostJsonSync(string url, object obj) {     
        var httpWebRequest         = (HttpWebRequest)WebRequest.Create(url);
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Method      = "POST";
    
        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) {
            var json = JsonConvert.SerializeObject(obj);
            streamWriter.Write(json);
            streamWriter.Flush();
            streamWriter.Close();
        }
    
        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) {
            var result = streamReader.ReadToEnd();
    
            return result;
        }
    }
    

    *note: It uses json.net for serialization.