0

我是在 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" }'

我的代码可能有什么问题?

4

2 回答 2

0

尝试

request.DefaultRequestHeaders.Authorization = 
    new AuthenticationHeaderValue(
        "Basic", Convert.ToBase64String(
            System.Text.ASCIIEncoding.ASCII.GetBytes(
               $"{client_id}")));
于 2020-08-26T12:25:25.900 回答
0

你需要使用

client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

代替

client.DefaultRequestHeaders.Add("Authorization", "Basic "+Convert.ToBase64String(clientCred));

例如 :

static async void HTTP_GET()
        {
            var TARGETURL = "http://en.wikipedia.org/";

            HttpClientHandler handler = new HttpClientHandler()
            {
                Proxy = new WebProxy("http://127.0.0.1:8888"),
                UseProxy = true,
            };

            Console.WriteLine("GET: + " + TARGETURL);

            // ... Use HttpClient.            
            HttpClient client = new HttpClient(handler);

            var byteArray = Encoding.ASCII.GetBytes("username:password1234");
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

            HttpResponseMessage response = await client.GetAsync(TARGETURL);
            HttpContent content = response.Content;

            // ... Check Status Code                                
            Console.WriteLine("Response StatusCode: " + (int)response.StatusCode);

            // ... Read the string.
            string result = await content.ReadAsStringAsync();

            // ... Display the result.
            if (result != null &&
            result.Length >= 50)
            {
                Console.WriteLine(result.Substring(0, 50) + "...");
            }
        }
    
于 2020-08-26T12:28:24.470 回答