Search code examples
c#jsonasp.net-mvchttpwebrequestwebrequest

Web request Content type is always text/html


I have a web api I need to use. This api will return the data according the content type I'm sending. Normally it will return html response. If the request has Content-Type header with the 'application/json' header it will return a json response.

When I try it using Postman and adding the content-type header (as application/json) everything is good. But when trying it using C# WebRequest object I'm always getting the html response regardless the content-type header I'm using. I've used fiddler to see the web request, and the content type is always text/html.

Here is my code. Tried this one:

    var webAddr = "https://xxxxxxxx.com/api/blabla";
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
        httpWebRequest.Method = "GET";

        httpWebRequest.Headers.Add("Authorization", "Basic xxxxxxxxxxx==");
        httpWebRequest.ContentType = "application/json; charset=utf-8";

        HttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse();


        Stream resStream = response.GetResponseStream();
        using (var reader = new StreamReader(resStream))
        {
            result = reader.ReadToEnd();
        }
        txtResult.Text = result;

Also tried this one:

var request = (HttpWebRequest)WebRequest.Create(EndPoint + parameters);

        request.Method = Method.ToString();
        request.ContentLength = 0;
        request.ContentType = "application/json";

            String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(userName + ":" + password));
            request.Headers.Add("Authorization", "Basic " + encoded);



        using (var response = (HttpWebResponse)request.GetResponse())
        {
            var responseValue = string.Empty;

            if (response.StatusCode != HttpStatusCode.OK)
            {
                var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
                return null;
            }

            // grab the response
            using (var responseStream = response.GetResponseStream())
            {
                if (responseStream != null)
                    using (var reader = new StreamReader(responseStream))
                    {
                        responseValue = reader.ReadToEnd();
                    }
            }

Still, every time, the content type is text/html.

Thanks in advance, Shaul


Solution

  • What you want to do is set the Accept headers, not Content-Type. Accept specifies the types of data you want to receive. Content-Type is for specifying the type of data you're sending.

    httpWebRequest.Accept = "application/json";