简体   繁体   中英

How can I include If-None-Match header in HttpRequestMessage

I have a HttpRequestMessage as follows:

string URI = "http://" + MyHostName.DisplayName.ToString() + "/datastore/";

HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, URI);
string Params = "";
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
request.Headers.AcceptCharset.Add(new StringWithQualityHeaderValue("utf-8", 0.7));
request.Headers.AcceptLanguage.Add(new StringWithQualityHeaderValue("en-us", 0.5));
request.Content = new StreamContent(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(Params)));
request.Content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

try
{
    var result = await client.SendAsync(request);
    var content = await result.Content.ReadAsStringAsync();
    return content.ToString();
}
catch (HttpRequestException)
{
    Connected = false;
    return "";
}

I want to add a If-None-Match header to my request with a value like '8001' as an example. But when I lookup HttpRequestHeaders.IfNoneMatch you can only get it and not set it.

Any Ideas?

Edit 1: Added that system is running UWP on Windows 10

Solution seemed to be a custom addition of a If-None-Match header

For future reference. It may be possible that a server does not accept an ETag in quotes like "8001".

To solve this you can use

            request.Headers.TryAddWithoutValidation("If-None-Match", "8001");

This will result in a If-None-Match tag of 8001

You can try

request.Headers.Add("If-None-Match", "\"8001\"");

or

request.Headers.IfNoneMatch.Add(new System.Net.Http.Headers.EntityTagHeaderValue("\"8001\""));

I have not tested the second one though.

Use the EntityTagHeaderValue.TryParse method to safely add an Etag. And be sure to wrap quotes around the string. If you receive an Etag value from a former request these are already included.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM