asp.net HttpClient请求的自定义标头

fnx2tebb  于 2023-05-30  发布在  .NET
关注(0)|答案(9)|浏览(238)

如何在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;
}
gk7wooem

gk7wooem1#

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

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

这应该会在请求中添加自定义标头

qc6wkl3g

qc6wkl3g2#

以下是基于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;
35g0bw71

35g0bw713#

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\"" },
            },
        },
    },
};
ubby3x7f

ubby3x7f4#

HttpRequestMessage类中有一个Headers属性。您可以在那里添加自定义头,它将与每个HTTP请求一起发送。另一方面,HttpClient类中的DefaultRequestHeaders设置了使用该客户端对象发送的每个请求所发送的头,因此名称为 Default Request Headers。
希望这能让事情更清楚,至少对将来看到这个答案的人来说。

kmbjn2e3

kmbjn2e35#

我在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);
xv8emn3q

xv8emn3q6#

我的两分钱。我同意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")

更多帮助:How to add request headers when using HttpClient

s4n0splo

s4n0splo7#

也可以使用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}");
      }
   }
}
ohfgkhjo

ohfgkhjo8#

如果有人想知道如何调用httpClient.GetStreamAsync(),它没有重载HttpRequestMessage来提供自定义头,您可以使用@Anubis给出的上述代码并调用
await response.Content.ReadAsStreamAsync()
如果您返回一个包含Range Header的blob url作为FileStreamResult,则此功能尤其有用

hiz5n14c

hiz5n14c9#

您可以使用System.Net.Http.Json.JsonContent,这是PostAsJsonAsync()内部的功能:

var jsonContent = JsonContent.Create(payload);
jsonContent.Headers.Add("X-custom-header", "Value");

var resp = await httpClient.PostAsync(uri, jsonContent);

这具有优于其他替代方案的优点:

  • 它使用优化的UTF-8序列化和应用程序配置的行为。
  • 它不设置DefaultRequestHeaders,这可能会影响其他不相关的查询。

相关问题