Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the Content-Type charset not exposed from HttpResponseMessage?

I'm converting some code from using HttpWebRequest to HttpClient. One problem I'm having is getting the charset from the content-type response header.

When using HttpWebRequest, the charset is exposed in the HttpWebResponse.CharacterSet property, like this

using (WebResponse response = await this.webRequest.GetResponseAsync())
{
     string characterSet = ((HttpWebResponse)response).CharacterSet;

You can also get to it from WebResponse.ContentType property or from the content-type header in HttpWebResponse.Headers.

Using HttpClient, the charset seems to be missing from the ContentType header.

Here's the code that I'm using for HttpClient:

using (HttpClient httpClient = new HttpClient(httpClientHandler))
{
    using (HttpResponseMessage httpResponseMessage = await httpClient.GetAsync(uri, HttpCompletionOption.ResponseContentRead))
    {
        charset = httpResponseMessage.Content.Headers.ContentType.CharSet;

The CharSet property is always null. HttpResponseMessage has a Headers property but it doesn't contain the content-type header. HttpResponseMessage.Content also has a Headers property, which does appear to contain the content-type header, but that header shows "Content-Type: text/html" - it doesn't have the charset portion.

Using the first approach with HttpWebResponse for the same url, I get the charset portion of the Content-Type header. Am I missing something?

like image 290
user2104834 Avatar asked Sep 29 '13 19:09

user2104834


2 Answers

I was looking to emit the charset inside a HttpResponseMessage and since your question is the first on google and that i found the answer several pages below, here is the code

httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
httpResponseMessage.Content.Headers.ContentType.CharSet = Encoding.UTF8.HeaderName;
httpResponseMessage.Content.Headers.Add("CodePage", Encoding.UTF8.CodePage.ToString());
like image 114
GELR Avatar answered Oct 27 '22 23:10

GELR


You can get it this way:

var contentType = response.Content.Headers.GetValues("Content-Type").First());
like image 29
DIG Avatar answered Oct 27 '22 22:10

DIG