如何解决如何在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的标头插入该网站。
我的代码是:
private static HttpClient _httpClient = new HttpClient();
var response = await _httpClient.GetAsync([myURI]);
因为该请求不包含我的密钥,所以出现401错误(未经授权的操作)。 我知道出了什么问题,但我不知道如何解决。我在GetAsync中看不到任何允许标头的地方。也许我应该使用其他方法?
基本上,我想将上面的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;
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。