In a validation setup I want to change the value of a header of a HttpRequestMessage
.
In a HttpClientHandler
I have the following code:
protected override async Task<HttpResponseMessage>
SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
//some condition when to alter the header
//does not work: value is read only
request.Headers.Single(c => c.Key == "FooHeader").Value =
new List<string>({"aha!"});
//does not work: cannot apply indexer
request.Headers["FooHeader"] = "aha!";
//does work but seems a bit overkill, besides I need to check if it exists
request.Headers.Remove("FooHeader");
request.Headers.Add("FooHeader", "aha!");
}
Is there a more intuitive way to achieve this?
To specify the content types of the request body and output, use the Content-Type and Accept headers. Indicates that the request body format is JSON. Indicates that the request body format is XML. Indicates that the request body is URL encoded.
get() The get() method of the Headers interface returns a byte string of all the values of a header within a Headers object with a given name. If the requested header doesn't exist in the Headers object, it returns null .
There is not better built-in way to replace headers. You could create an extension method to do this in more fluent way:
public static class HttpRequestHeadersExtensions
{
public static void Set(this HttpRequestHeaders headers, string name, string value)
{
if (headers.Contains(name)) headers.Remove(name);
headers.Add(name, value);
}
}
Then you can use it like:
request.Headers.Set("FooHeader", "aha!");
request.Headers.Set("FooHeader", "ahaha!");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With