Почему HttpClient использует неправильный requestUri в почтовом запросе? - PullRequest
0 голосов
/ 26 августа 2018

Когда я использую класс HttpClient для отправки запроса POST на URL API, он изменяет URL, который я ему передал.Например, когда я использую основной URL-адрес API, RequestUri неверен, и я получаю не найденный ответ.Эта проблема возникает, когда я использую api слово в URL! *

Концепция:

The Incorrect, modified URL:

Url: https://sandbox-api.alopeyk.com/api/v2/order 
Request Url: https://sandbox-api.alopeyk.com

The Correct, and expected URL (This is the one I specify)

Url: https://google.com/api/v2/order
Request Url: https://google.com/api/v2/order

Код:

public async Task<CreateOrderResponse> CreateOrderAsync(CreateOrderRequest request)
{
     var endPoint = EndPointFactory<CreateOrderResponse>.Build(HttpMethod.Post);

    var jsonString = JsonConvert.SerializeObject(request);

    var url = new Uri("https://sandbox-api.alopeyk.com");

    var encodedFrom = new StringContent(jsonString);

    var httpClient = endPoint.GetHttpClient(url);

    var httpResponse = await httpClient.PostAsync("api/v2/orders", encodedFrom).ConfigureAwait(false);

    // when use api it's https://sandbox-api.alopeyk.com it should be https://sandbox-api.alopeyk.com/api/v2/orders
    // when use other host name for example it's correct
    var requesturl = httpResponse.RequestMessage.RequestUri;

    return await httpResponse.Content.ReadAsAsync<CreateOrderResponse>().ConfigureAwait(false);
}

 // in the EndPoint class
 public HttpClient GetHttpClient(Uri url)
 {
     return new Http.HttpClientFactory().GetOrCreate(Url, Headers);
 }

Есливы хотите видеть HttpClientFactory здесь здесь .

У HttpClient есть проблема с моим основным именем хоста, что это https://sandbox-api.alopeyk.com

Ответы [ 3 ]

0 голосов
/ 26 августа 2018

Ваш Uri должен заканчиваться слешем так:

  var url = new Uri("https://sandbox-api.alopeyk.com/");

Это довольно глупое ограничение HttpClient.

0 голосов
/ 26 августа 2018

Попробуйте этот код:

 HttpClient client = new HttpClient();
   client.BaseAddress = new Uri("https://sandbox-api.alopeyk.com");
   HttpResponseMessage response = client.PostAsync("api/v2/orders", new StringContent(jsonString, Encoding.UTF8, "text/json")).Result;  
                if (response.IsSuccessStatusCode)
                {
                    // Parse the response body. Blocking!
                   var  responseData = response.Content.ReadAsStringAsync().Result;                    

                }
0 голосов
/ 26 августа 2018

Вы можете попробовать с этим кодом

HttpResponseMessage response = null;
            using (var client = new HttpClient())
            {
                using (var request = new HttpRequestMessage(HttpMethod.Post,"https://sandbox-api.alopeyk.com/api/v2/orders"))
                {
                    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", /*token herer*/);
                    var data = new StringContent(JsonConvert.SerializeObject(request, Encoding.UTF8, "application/json"));
request.Content = data;
                    response = await client.SendAsync(request);
                }
            }
...