Custom header to HttpClient request

前端 未结 4 1738
走了就别回头了
走了就别回头了 2020-11-27 03:38

How do I add a custom header to a HttpClient request? I am using PostAsJsonAsync method to post the JSON. The custom header that I would need to b

4条回答
  •  囚心锁ツ
    2020-11-27 04:07

    Here is an answer based on that by Anubis (which is a better approach as it doesn't modify the headers for every request) but which is more equivalent to the code in the original question:

    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 xxxxxxxxxxxxxxxxxxxx" },
                    { HttpRequestHeader.Accept.ToString(), "application/json" },
                    { "X-Version", "1" }
                },
                Content = new StringContent(JsonConvert.SerializeObject(svm))
            };
    
        var response = client.SendAsync(httpRequestMessage).Result;
    

提交回复
热议问题