自定义HttpClient请求头

如何向HttpClient请求添加自定义标头?我使用PostAsJsonAsync方法发布JSON。我需要添加的自定义标头是

"X-Version: 1"

这是我目前所做的:

using (var client = new HttpClient()) {
client.BaseAddress = new Uri("https://api.clickatell.com/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "xxxxxxxxxxxxxxxxxxxx");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.PostAsJsonAsync("rest/message", svm).Result;
}
300680 次浏览

我已经找到了问题的答案。

client.DefaultRequestHeaders.Add("X-Version","1");

这将为您的请求添加一个自定义标头

var request = new HttpRequestMessage {
RequestUri = new Uri("[your request url string]"),
Method = HttpMethod.Post,
Headers = {
{ "X-Version", "1" } // HERE IS HOW TO ADD HEADERS,
{ HttpRequestHeader.Authorization.ToString(), "[your authorization token]" },
{ HttpRequestHeader.ContentType.ToString(), "multipart/mixed" },//use this content type if you want to send more than one content type
},
Content = new MultipartContent { // Just example of request sending multipart request
new ObjectContent<[YOUR JSON OBJECT TYPE]>(
new [YOUR JSON OBJECT TYPE INSTANCE](...){...},
new JsonMediaTypeFormatter(),
"application/json"), // this will add 'Content-Type' header for the first part of request
new ByteArrayContent([BINARY DATA]) {
Headers = { // this will add headers for the second part of request
{ "Content-Type", "application/Executable" },
{ "Content-Disposition", "form-data; filename=\"test.pdf\"" },
},
},
},
};

HttpRequestMessage类中有一个Headers属性。您可以在那里添加自定义报头,它将随每个HTTP请求一起发送。另一方面,HttpClient类中的DefaultRequestHeaders设置使用该客户端对象发送的每个请求发送的标头,因此命名为默认的请求标头。

希望这能让事情更清楚,至少对将来看到这个答案的人来说。

以下是基于Anubis的回答(这是一个更好的方法,因为它不修改每个请求的头),但更相当于原始问题中的代码:

using Newtonsoft.Json;
...


var client = new HttpClient();
var httpRequestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri("https://api.clickatell.com/rest/message"),
Headers = {
{ HttpRequestHeader.Authorization.ToString(), "Bearer xxxxxxxxxxxxxxxxxxx" },
{ HttpRequestHeader.Accept.ToString(), "application/json" },
{ "X-Version", "1" }
},
Content = new StringContent(JsonConvert.SerializeObject(svm))
};


var response = client.SendAsync(httpRequestMessage).Result;

我在HttpClient头文件中添加了x-api-version,如下所示:

var client = new HttpClient(httpClientHandler)
{
BaseAddress = new Uri(callingUrl)
};
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("x-api-version", v2);

如果有人想知道如何调用httpClient.GetStreamAsync(),它没有重载,需要HttpRequestMessage来提供自定义头,您可以使用@Anubis给出的上述代码并调用

await response.Content.ReadAsStreamAsync()

特别有用,如果你返回一个blob url范围头作为一个FileStreamResult

我的意见。我同意heug的观点。公认的答案是令人费解的。让我们后退一步。

默认头应用于特定HttpClient发出的所有请求。因此,您将为共享头文件使用默认头文件。

_client.DefaultRequestHeaders.UserAgent.ParseAdd(_options.UserAgent);

然而,我们有时需要特定于某个请求的头文件。因此,我们将在方法中使用类似这样的东西:

public static async Task<HttpResponseMessage> GetWithHeadersAsync(this
HttpClient httpClient, string requestUri, Dictionary<string, string> headers)
{
using (var request = new HttpRequestMessage(HttpMethod.Get, requestUri))
{
foreach(var header in headers)
{
request.Headers.Add(header.Key, header.Value);
}


return await httpClient.SendAsync(request);
}
}

如果你只需要一个额外的非默认头,你可以简单地使用:

request.Headers.Add("X-Version","1")

更多帮助: 如何添加请求头时使用HttpClient < / p >

你也可以使用HttpClient。PostAsync方法:

using (HttpClient http_client = new HttpClient())
{
StringContent string_content = new StringContent(JsonSerializer.Serialize("{\"field\":\"field_value\"}"));
string_content.Headers.Add("X-Version","1");
using (HttpResponseMessage response = await http_client.PostAsync("http://127.0.0.1/apiMethodName", string_content))
{
if (response.IsSuccessStatusCode)
{
Console.WriteLine($"Response status code: {response.StatusCode}");
}
else
{
Console.WriteLine($"Error status code: {response.StatusCode}");
}
}
}