headerhttpwebrequestcontent-typecontenttype

How to corectly set the ContentType property in HttpWebRequest (or how to fix the missing Content-Type header)


I thought I'd share something that took me some time to figure out:

I wrote a simple Post method using HttpWebRequest class. In HttpWebRequest you can't use HttpWebRequest.Headers collection to set your desired headers when there is a dedicated property for it - you must use that dedicated property. ContentType is one of them. So I created my HttpWebRequest like this:

            HttpWebRequest httpWebRequest = (HttpWebRequest)webRequest;
            httpWebRequest.Method = "POST";
            httpWebRequest.KeepAlive = false;
            httpWebRequest.ServicePoint.Expect100Continue = false;
            httpWebRequest.ContentType = "application/json";

somewhere below I set the body of my request like this:

            using (StreamWriter streamWriter = new StreamWriter(streamWebRequest))
            {
                streamWriter.Write(sJson);
            }

and posted the request using:

            WebResponse webResponse = httpWebRequest.GetResponse();

But I kept getting a "400 - Bad Request" error, while the same request worked from Postman. After analyzing the request with Fiddler I found that when I send the request from my app, the Content-Type: application/json header is missing. All the other headers were present, except for Content-Type. I thought I'm setting it wrong, so I googled but didn't find a good answer. After much experimentation I found, that if I move the line:

            httpWebRequest.ContentType = "application/json"

after this block:

            using (StreamWriter streamWriter = new StreamWriter(streamWebRequest))
            {
                streamWriter.Write(sJson);
            }

then the httpWebRequest.ContentType = "application/json" header finally appears in the request. So, for HttpWebRequest make sure you always set your HttpWebRequest's body/content first, before you set the ContentType property.

Hope it helps


Solution

  • My question above already has the answer, but to mark it as "Answered" I had to add this comment:

    Make sure you always set your HttpWebRequest's body/content first, before you set the ContentType property.This way the "Content-Type" header will appear in the request.