0

I'm trying to get the value of the Content-Type content header on an HTTP response.

private async void StartButton_Click(object sender, EventArgs e)
{
    var client = new HttpClient();

    // When I send a GET request to this website and print the response
    var response = await client.GetAsync("https://www.npr.org/sections/13.7/2017/12/01/567727098/a-tax-that-would-hurt-sciences-most-valuable-and-vulnerable");
    Console.WriteLine(response);
    // [BELOW] You can clearly see: Content-Type: text/html;;charset=UTF-8

    // However, the value is malformed (note the double semicolon) and becomes null
    Console.WriteLine(response.Content.Headers.ContentType == null);
    // True
}

StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  Access-Control-Allow-Origin: *
  Access-Control-Allow-Credentials: true
  X-Content-Type-Options: nosniff
  X-XSS-Protection: 1; mode=block
  Referrer-Policy: no-referrer-when-downgrade
  Strict-Transport-Security: max-age=604800; includeSubDomains
  X-Frame-Options: SAMEORIGIN
  Transfer-Encoding: chunked
  Connection: keep-alive
  Connection: Transfer-Encoding
  Cache-Control: max-age=0
  Date: Tue, 19 Jun 2018 10:38:01 GMT
  Server: Apache
  X-Powered-By: PHP/5.6.33
  Content-Type: text/html;;charset=UTF-8
  Expires: Tue, 19 Jun 2018 10:38:01 GMT
  Last-Modified: Fri, 01 Dec 2017 15:41:00 GMT
}

How can I repair the malformed value of the Content-Type so it becomes text/html; charset=UTF-8 instead of null?

I tried to explain my question as simply as possible. If you have any questions or think I left something out, please let me know! :)

Owen
  • 321
  • 2
  • 12
  • You can't. You need to specify the Content-Type in the Request. When you send a request the headers are use to negotiate a common set of properties between the client and server. In this case you are not send int a Content-Type so the server doesn't know what encoding you are using and sending back null. So add Content-Type to your request. – jdweng Jun 19 '18 at 11:05
  • 1
    Have you tried `response.Headers.GetValues("Content-Type")` to read it? – Crowcoder Jun 19 '18 at 11:06
  • @Crowcoder You lead me to figuring out the answer, although it seems needlessly sloppy. – Owen Jun 19 '18 at 11:29

1 Answers1

0

Thanks to Crowcoder's comment, I was able to develop the answer. Although, I feel like it's sloppy and could be made elegant.

private async void StartButton_Click(object sender, EventArgs e)
{
    var client = new HttpClient();
    var response =
        await client.GetAsync(
            "https://www.npr.org/sections/13.7/2017/12/01/567727098/a-tax-that-would-hurt-sciences-most-valuable-and-vulnerable");
    Console.WriteLine(string.Join("; ",
        response.Content.Headers.GetValues("Content-Type").First()
            .Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)));
}

// text/html; charset=UTF-8
Owen
  • 321
  • 2
  • 12