我是在 C# 中编写泛型方法的新手,我正在尝试SendAsync
在我的 C# 项目中创建一个泛型方法。代码如下。
HttpClientHelper.cs
public static async Task<TOut> ExecuteRequest<TIn,TOut>(TIn request, string url)
{
Uri requestUri = new Uri(url);
string payload = JsonConvert.SerializeObject(request);
HttpContent httpContent = new StringContent(payload, Encoding.UTF8, "application/json");
HttpRequestMessage requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = requestUri,
Content = httpContent
};
return await SendUriAsync<TOut>(requestMessage);
}
public static async Task<T> SendUriAsync<T>(HttpRequestMessage requestMessage)
{
CancellationTokenSource source = new CancellationSource();
CancellationToken token = source.Token;
string client_id = "1234";
using (var client = new HttpClient())
{
var clientCred = Encoding.UTF8.GetBytes($"{client_id}");
client.DefaultRequestHeaders.Add("Authorization", "Basic "+Convert.ToBase64String(clientCred));
using(var result = await client.SendAsync(requestMessage, token))
{
result.EnsureSuccessStatusCode();
var response = await result.Content.ReadAsStringAsync();
if(result.IsSuccessStatusCode && response != null)
{
return JsonConvert.DeserializeObject<T>(response);
}
else
{
throw new ApiException{ status = (int)result.StatusCode};
}
}
}
}
这是调用这些方法的控制器类:
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" }'
我的代码可能有什么问题?