Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change a header value of HttpRequestMessage

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?

like image 643
Stefan Avatar asked Apr 28 '17 10:04

Stefan


People also ask

How do I change the content-type in an HTTP header?

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.

How do I find a header value?

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 .


1 Answers

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!");
like image 169
Andrii Litvinov Avatar answered Sep 28 '22 02:09

Andrii Litvinov