如何在C#中使用PostAsync设置多个标头?

时间:2015-03-23 17:26:24

标签: c# httpresponse

我有一些工作代码:

using (var client = new HttpClient())
{
HttpResponseMessage response;
response = client.PostAsync(Url, new StringContent(Request, Encoding.UTF8, header)).Result;
}

//上述方法适用于简单的标题,例如"应用/ JSON"

如果我想要多个标题,该怎么办?例如。添加" myKey"," foo"对和"接受"," image / foo1"

如果我尝试在.Result行之前添加以下内容,则intellisense会抱怨(单词' Headers'用红色表示"无法解析符号' Headers&#39 ;":

client.Headers.Add("myKey", "foo");
client.Headers.Add("Accept", "image/foo1");

3 个答案:

答案 0 :(得分:25)

您可以通过Headers

访问StringContent媒体资源
var content = new StringContent(Request, Encoding.UTF8, header);
content.Headers.Add(...);

然后将StringContent传递给PostAsync调用:

response = client.PostAsync(Url, content).Result;

答案 1 :(得分:18)

我停止使用Post / Get * Async方法支持SendAsync(...)方法和HttpRequestMessage 发送异步是一个大哥,它可以让你获得你无法实现的全部灵活性。

using System.Net.Http;

var httpRequestMessage = new HttpRequestMessage();

httpRequestMessage.Method = httpMethod;
httpRequestMessage.RequestUri = new Uri(url);

httpRequestMessage.Headers
                  .UserAgent
                  .Add(new Headers.ProductInfoHeaderValue(
                                              _applicationAssembly.Name, 
                                              _applicationAssembly.Version.ToString()));

HttpContent httpContent = new StringContent(json, Encoding.UTF8, "application/json");
switch (httpMethod.Method)
{
    case "POST":
        httpRequestMessage.Content = httpContent;
        break;
}

var result = await httpClient.SendAsync(httpRequestMessage);
result.EnsureSuccessStatusCode();

答案 2 :(得分:3)

您也可以使用

var client = new HttpClient();
client.DefaultRequestHeaders.TryAddWithoutValidation("headername","headervalue");

如果您只想在HttpClient类上设置标题一次。以下是DefaultRequestHeaders.TryAddWithoutValidation

上的MSDN docs