自定义标头到Httpclient请求

时间:2016-03-10 04:32:19

标签: c# asp.net http-headers dotnet-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;
}

4 个答案:

答案 0 :(得分:149)

我找到了问题的答案。

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

这应该为您的请求添加自定义标头

答案 1 :(得分:37)

var request = new HttpRequestMessage {
    RequestUri = new Uri(EnvironmentSetup.BaseAddress + "Folder"),
    Method = HttpMethod.Post,
    Headers = {
        { HttpRequestHeader.Authorization.ToString(), "Basic " + EnvironmentSetup.GetAuthToken() },
        { HttpRequestHeader.ContentType.ToString(), "multipart/mixed" },
    },
    Content = new MultipartContent {
        new ObjectContent<FolderWithDocuments>(new FolderWithDocuments {
            Status = FolderStatus.Draft,
            Users = new List<User> { EnvironmentSetup.User1, EnvironmentSetup.User2 },
        }, new JsonMediaTypeFormatter(), "application/json"),
        new ByteArrayContent(ResourceHelper.ReadResourceToByteArray("blank.pdf")) {
            Headers = {
                { "Content-Type", "application/Executable" },
                { "Content-Disposition", "form-data; filename=\"test.pdf\"" },
            },
        },
    },
};

答案 2 :(得分:27)

这是基于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 xxxxxxxxxxxxxxxxxxxx" },
                { HttpRequestHeader.Access.ToString(), "application/json" },
                { "X-Version", "1" }
            },
            Content = new StringContent(JsonConvert.SerializeObject(svm))
        };

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

答案 3 :(得分:0)

Headers类中有一个HttpRequestMessage属性。您可以在此处添加自定义标头,该标头将与每个HTTP请求一起发送。另一方面,DefaultRequestHeaders类中的HttpClient设置要与使用该客户端对象发送的每个请求一起发送的标头,因此名称为 Default Request Headers。

希望这使事情变得更清楚,至少对于将来会看到此答案的人来说。