WJM
WJM

Reputation: 1201

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

Upvotes: 3

Views: 7636

Answers (3)

Bram Hoekman
Bram Hoekman

Reputation: 11

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.

Upvotes: 0

WJM
WJM

Reputation: 1201

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

Upvotes: 3

Parthasarathy
Parthasarathy

Reputation: 2818

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.

Upvotes: 1

Related Questions