Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

http

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

like image 774
WJM Avatar asked Dec 31 '25 10:12

WJM


2 Answers

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

like image 134
WJM Avatar answered Jan 01 '26 23:01

WJM


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.

like image 45
Parthasarathy Avatar answered Jan 01 '26 22:01

Parthasarathy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!