我是在 C# 中编写泛型方法的新手,我正在尝试SendAsync
在我的 C# 项目中创建一个泛型方法。代码如下。
HttpClientHelper.cs
public static async Task<T2t> ExecuteRequest<T1,T2>(T2 request, string url)
{
Uri requestUri = new Uri(url);
string payload = JsonConvert.SerializeObject(request);
HttpContent httpContent = new StringContent(payload, "application/json");
HttpRequestMessage requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = requestUri,
Content = httpContent
};
return await SendUriAsync<T2>(requestMessage);
}
public static async Task<T> SendUriAsync<T>(HttpRequestMessage requestMessage)
{
string clint_id = "1234";
var clineCred = Encoding.UTF8.GetBytes($"{client_id}");
using(var result = await client.SendAsync(requestMessage))
{
result.EnsureSuccessStatusCode();
var response = await result.Content.ReadAsStringAsync();
if(result.IsSuccessStatusCode && response != null)
{
return JsonConvert.DeserializeObject<T>(response);
}
else
{
return null;
}
}
}
这是调用这些方法的控制器类:
CarSalesController.cs
string thirdpartyUrl = "someurl";
var responseObject = await HttpClientHelper.ExecuteRequest<CarObject, string>(requestObject, thirdpartyUrl);
我在HttpClientHelper
课堂上遇到错误。错误是:
ResponseStatusCode 不表示成功。状态码:401 - 未经授权
但是当我使用邮递员时,相同的 API 效果很好。他是卷曲
curl --location --request GET 'someurl'
--header 'client_id:1234'
--header '授权:基本 asdf'
--header 'Content-Type: application/json'
--data-raw '{ "data1" :"somedata1", "data2":"somedata2" }'
我的代码可能有什么问题?