我正在尝试从我的C#代码中的外部应用程序调用api。 (.Net核心2.2)
我为此使用HttpClient
。当我尝试将Expires
添加到标头时,它在被调用时已从请求中删除(我通过Fiddler进行了检查)。我以类似的方式添加了身份验证令牌,并且该令牌已正确添加到标头中。
我从api中收到401
错误。
以下是我的代码:
HttpClient client = new HttpClient();
var req = new HttpRequestMessage(HttpMethod.Get, requestUri.Uri);
var xml = new MediaTypeWithQualityHeaderValue("application/xml");
var json = new MediaTypeWithQualityHeaderValue("application/json", 0.8);
req.Headers.Accept.Clear();
req.Headers.Accept.Add(json);
// First try
//req.Headers.TryAddWithoutValidation("Authorization", "H** ********:MApmTuFFV5nZJOg+i5gRBPkM**0=");
//req.Headers.TryAddWithoutValidation("Expires", "10/02/19 10:36:33 AM UTC");
// Second try
//client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "H** ********:MApmTuFFV5nZJ**+i5gRBPkM**0=");
//client.DefaultRequestHeaders.TryAddWithoutValidation("Expires", "10/02/19 10:36:33 AM UTC");
// Third try
//req.Headers.Authorization = new AuthenticationHeaderValue("Authorization", "H** ********:MApmTuFFV5nZJOg+i5gRBPkM**0=");
// req.Headers.Add("Expires", "10/02/19 10:36:33 AM UTC");
try
{
using (HttpResponseMessage res = await client.SendAsync(req))
{
response.ResponseStatusCode = res.StatusCode;
response.ResponseStatusDescription = string.Format("HttpStatusCode: {0} \n StatusDescription: {1}", res.StatusCode.ToString(), res.StatusCode);
using (var reader = new StreamReader(await res.Content.ReadAsStreamAsync()))
{
response.ResponseContent = reader.ReadToEnd();
}
}
}
catch (Exception ex)
{
}
使用HttpWebRequest
完成了api调用,并且效果很好,当我将其更改为HttpClient
时,得到了401 UnAuthorized
作为api的响应:
较早的代码是:
string uri = "http://someservice.com"
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
req.Method = "Get";
req.Accept = "application/json";
req.KeepAlive = true;
req.Headers[HttpRequestHeader.Expires] = "10/02/19 10:36:33 AM UTC";
req.Headers[HttpRequestHeader.Authorization] = "H** ********:MApmTuFFV5nZJ**+i5gRBPkM**0=";
try
{
using (HttpWebResponse res = (HttpWebResponse)req.GetResponse())
{
response.ResponseStatusCode = res.StatusCode;
response.ResponseStatusDescription = string.Format("HttpStatusCode: {0} \n StatusDescription: {1}", res.StatusCode.ToString(), res.StatusDescription);
using (var reader = new StreamReader(res.GetResponseStream()))
{
response.ResponseContent = reader.ReadToEnd();
}
}
}
有人可以指出我的方法中的问题吗?