[英]how to add more details to a Task returned by HttpClient.GetAsync
[英]how to add header to GetAsync in httpclient
我必須將一個 ps 項目轉換為 C# 並且我不熟悉在 C# 中訪問 webapi 的操作下面是 PS 中一直像魅力一樣工作的代碼。
PowerShell 代碼:
$api_key = [myKey]
$header = @{"x-api-key"=$api_key}
$uri = [myURI]
$resp = invoke-webrequest -uri $uri -method get -headers
在 C# 中,我使用 HttpClient 和 GetAsync 方法來檢索資源。 我的問題是我不確定如何將包含我的 apiKey 的 header 插入網站。
我的代碼是:
private static HttpClient _httpClient = new HttpClient();
var response = await _httpClient.GetAsync([myURI]);
因為請求不包含我的密鑰,所以我收到 401 錯誤(未經授權的操作)。 我知道出了什么問題,但我不知道如何解決。 我在 GetAsync 中看不到任何允許 header 的地方。 也許我應該使用不同的方法?
基本上,我想將上面的 PS 片段轉換為 C# .netcore。
請指教。
您應該使用HttpRequestMessage
模式來執行此操作。 例如:
using (var msg = new HttpRequestMessage(HttpMethod.Get, fromUri))
{
msg.Headers.Add("x-header-test", "the value");
using (var resp = await _client.SendAsync(msg))
{
resp.EnsureSuccessStatusCode();
return await resp.Content.ReadAsStringAsync();
}
}
使用 (var httpClient = new HttpClient()) {
httpClient.DefaultRequestHeaders.Add("token", "sample token");
JObject data = JObject.Parse(inputData);
var content = new StringContent(JsonConvert.SerializeObject(data, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore })); //using Newtonsoft.Json
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await httpClient.PostAsync(url, content).ConfigureAwait(false);
await response.Content.ReadAsStringAsync().ContinueWith((Task<string> x) =>
{
if (!response.IsSuccessStatusCode)
{
throw new Exception(x.Result);
}
else
{
JObject output = x.Result;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.