我正在尝试在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
}
我试图尽可能简单地解释我的问题。如果您有任何疑问或认为我遗漏了某些问题,请告诉我们! :)
答案 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