簡體   English   中英

C#Flurl和HttpClient,REST API沒有響應

[英]C# Flurl and HttpClient, no response from REST API

我在使用我的代碼從API獲取響應時遇到問題,請求沒有超時,它根本沒有給我回復。 我已經在我自己的API中創建了一個api端點來返回json字符串然后用“Firefox Poster”手動發布json數據,它運行得很好。 有了這個,我相信問題出現在我的代碼中。

我得到了一個C#WebAPI,我正在開發它與Angular前端一起使用(這是有效的,它僅用於歷史)。 在調用我的API時,我創建了對象“EnrollmentRequestDto”

public class EnrollmentRequestDto
{
    /// <summary>
    /// Context Information for the request. Contains the Ship-To, language code and timezone.
    /// </summary>
    [JsonProperty("requestContext")]
    public RequestContextDto RequestContext { get; set; }
    /// <summary>
    /// Unique ID provided by DEP to reseller on provisioning DEP access. This would be the reseller's DEP ID if its posted by distributor OBO a reseller, and would be his own depResellerId if a reseller is posting for self.
    /// </summary>
    [JsonProperty("depResellerId")]
    public string DepResellerId { get; set; }
    /// <summary>
    /// Unique transaction ID provided by the reseller
    /// </summary>
    [JsonProperty("transactionId")]
    public string TransactionId { get; set; }
    /// <summary>
    /// List of orders in the transaction (limit 1000 per transaction)
    /// </summary>
    [JsonProperty("orders")]
    public List<OrderDto> Orders { get; set; }
}

創建此對象后,我發送到我的類RequestHandler和方法BulkEnrollRequest,其中atm是用HttpClient擴展名Flurl編寫的,可以在這里找到: github

public IResponse BulkEnrollRequest(EnrollmentRequestDto enrollmentRequest)
    {
        try
        {
            var result = _bulkEnrollUrl.PostJsonAsync(enrollmentRequest).ReceiveJson<SuccessResponse>();
            result.Wait();
            return result.Result;
        }
        catch (FlurlHttpTimeoutException)
        {
            throw new AppleTimeOutException();
        }
        catch (FlurlHttpException ex)
        {
            return _errorHandler.DeserializeFlurlException(ex);
        }
    }

我也試過這個以確保在Flurl中沒有任何反應(這只是為了調試到我想要獲得響應的程度):

public async Task<IResponse> BulkEnrollRequest(EnrollmentRequestDto enrollmentRequest)
    {
        var json = JsonConvert.SerializeObject(enrollmentRequest);

        var httpClient = new HttpClient();
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        HttpResponseMessage response = await httpClient.PostAsync(_bulkEnrollUrl, new StringContent(json, Encoding.UTF8, "application/json"));

        return new SuccessResponse();
    }

代碼在等待點凍結,沒有任何事情發生。 我試圖在BulkEnrollRequest之后放置一個斷點,所以它永遠不會離開這個方法。

現在這里是有趣的部分:它在我正在使用ErrorHandler時工作,並且在某些時候API剛剛停止響應。 Wireshark顯示正在提出請求......所以我被困住了。

任何幫助表示贊賞。

編輯

這現在有效! 我從API控制器到RequestHandler一直實現異步 ,然后等待每次調用。 以供參考:

public async Task<IResponse> BulkEnrollRequest(EnrollmentRequestDto enrollmentRequest)
    {
        try
        {
            var result = await _bulkEnrollUrl.PostJsonAsync(enrollmentRequest).ReceiveJson<SuccessResponse>();
            return result;
        }
        catch (FlurlHttpTimeoutException)
        {
            throw new AppleTimeOutException();
        }
        catch (FlurlHttpException ex)
        {
            return _errorHandler.DeserializeFlurlException(ex);
        }
    }

這已經修復了。 我相信Wireshark流量看起來如此奇怪的原因是由於代碼中的死鎖,並且超時在我身邊,這意味着我永遠無法確認信息。 為了解決這個問題,我在所有方法上實現了異步 ,從Controller到我的RequestHandler類。 以供參考:

public async Task<IResponse> BulkEnrollRequest(EnrollmentRequestDto enrollmentRequest)
    {
        try
        {
            var result = await _bulkEnrollUrl.PostJsonAsync(enrollmentRequest).ReceiveJson<SuccessResponse>();
            return result;
        }
        catch (FlurlHttpTimeoutException)
        {
            throw new AppleTimeOutException();
        }
        catch (FlurlHttpException ex)
        {
            return _errorHandler.DeserializeFlurlException(ex);
        }
    }

試試這個代碼

安裝包Microsoft.AspNet.WebApi.Client

 using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:9000/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = await client.PostAsJsonAsync("api/products", enrollmentRequest);
            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadAsAsync<T>();
            }
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM