如何修复HTTP响应中标头的格式错误值?

时间:2018-06-19 10:52:20

标签: c# http-headers httprequest httpresponse response-headers

我正在尝试在HTTP响应中获取 Content-Type 内容标头的值。

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
}

如何修复 Content-Type 的格式错误的值,使其变为 text / html; charset = UTF-8 而不是null?

我试图尽可能简单地解释我的问题。如果您有任何疑问或认为我遗漏了某些问题,请告诉我们! :)

1 个答案:

答案 0 :(得分:0)

由于Crowcoder的评论,我得以找到答案。虽然,我觉得它马虎,可以做得很优雅。

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