仅为POST请求添加默认标头

时间:2020-02-18 01:17:04

标签: c# http asp.net-core asp.net-core-mvc asp.net-core-3.1

我正在尝试使用Typed HttpClient,如下所示。我正在寻找一种方法,仅将DefaultRequestHeaders添加到我的POST请求中(而不添加到其他请求,例如GETPUT)。有办法实现吗?

这是我的代码段。

var builder = services
     .AddHttpClient("MyService", client =>
      {
         client.BaseAddress = configuration.BaseAddress;

         // Need to default header only for "POST" request                    
         client.DefaultRequestHeaders.Add("MyHeader", "MyHeaderValue");
      })
      .AddTypedClient<IMyServiceClient, MyServiceRestClient>();

我正在尝试找到一种方法,其中行client.DefaultRequestHeaders.Add("MyHeader", "MyHeaderValue")仅对POST请求有效。

2 个答案:

答案 0 :(得分:0)

具有最少配置,然后通过特定于http方法的执行来管理您的请求的可重用 httpclient 怎么样?

例如,考虑一个异步POST方法,该方法将覆盖配置请求/响应并使用您的 httpclient 执行的内部通用异步方法。您可以传入所需的标头和/或在此方法中设置默认标头。

public async Task<KeyValuePair<HttpResponseMessage, T>> PostAsync<T>(Uri uri, object data, AuthenticationHeaderValue authHeader = null, Dictionary<string, string> headers = null)
{
   return await SendRequestAsync<T, object>(uri.ToString(), data, HttpMethod.Post, authHeader, headers);
}

内部方法如下:

private async Task<KeyValuePair<HttpResponseMessage, T>> SendRequestAsync<T, U>(string requestUri, U content, HttpMethod method, AuthenticationHeaderValue authHeader = null, Dictionary<string, string> headers = null)
{
    using (HttpRequestMessage request = new HttpRequestMessage())
    {
        request.Method = method;
        request.RequestUri = new Uri(requestUri, UriKind.Absolute);

        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        if (authHeader != null)
        {
            request.Headers.Authorization = authHeader;
        }

        string requestContent = null;

        if (content != null)
        {
            requestContent = JsonConvert.SerializeObject(content);
            request.Content = new StringContent(requestContent, Encoding.UTF8, "application/json");
        }

        if (headers != null)
        {
            foreach (var header in headers)
            {
                if (!request.Headers.Contains(header.Key))
                {
                    request.Headers.Add(header.Key, header.Value);
                }
            }
        }

        // _client would be a private implementation or injected version of your httpclient
        using (HttpResponseMessage response = await _client.SendAsync(request))
        {
            if (response.IsSuccessStatusCode)
            {
                if (response.Content != null)
                {
                    var rawJson = await response.Content.ReadAsStringAsync();

                    var mappedObj = JsonConvert.DeserializeObject<T>(rawJson);

                    var result = new KeyValuePair<HttpResponseMessage, T>(response, mappedObj);

                    return result;
                }
            }
            else
            {
                // do something else
            }

            return new KeyValuePair<HttpResponseMessage, T>(response, default(T));
        }
    }
}

答案 1 :(得分:0)

我在这里实际上很愚蠢。我意识到我可以通过// this is correct, SocketMessage is the type parameter that Filter expects private async Task Filter(SocketMessage arg) { } public async Task StartInterpretation() { var arg = new SocketMessage(); // do not specify the type parameter, just pass the variable await Filter(arg); } 实现自己想要的目标。

DelegatingHandler