将身份验证标头添加到HttpClient

时间:2015-03-19 00:59:52

标签: c# dotnet-httpclient

我试图访问API,但所有文档都使用PHP,而且我对PHP不是很熟悉。我无法对API进行身份验证。 documentation is here

这是我到目前为止所拥有的

var webAddress = "https://xboxapi.com/v2/latest-xbox360-games";

var httpResponse = (new HttpClient().GetAsync(webAddress)).Result;
httpResponse.EnsureSuccessStatusCode();
var jsonResponse = httpResponse.Content.ReadAsStringAsync().Result;

我只是不确定如何添加他们在PHP中使用的身份验证标头。

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:3)

要添加自定义标头(在本例中为X-AUTH),您需要发送自定义HttpRequestMessage。例如:

var webAddress = "https://xboxapi.com/v2/latest-xbox360-games";

HttpClient client = new HttpClient();
HttpRequestMessage msg = new HttpRequestMessage(HttpMethod.Get, webAddress);
msg.Headers.Add('X-AUTH', 'your-auth-key-here');

HttpResponseMessage response = await client.SendAsync(msg);