如何更改HttpRequestMessage的标头值

时间:2017-04-28 10:56:13

标签: c# .net httprequest

在验证设置中,我想更改HttpRequestMessage的标头值。

HttpClientHandler我有以下代码:

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!");
}

有更直观的方法来实现这一目标吗?

1 个答案:

答案 0 :(得分:7)

没有更好的内置方法来替换标头。您可以创建一个扩展方法,以更流畅的方式执行此操作:

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);
    }
}

然后你就可以使用它:

request.Headers.Set("FooHeader", "aha!");
request.Headers.Set("FooHeader", "ahaha!");