我使用HttpClient向API发出GET请求,该请求应返回JSON数据,但我的请求被卡在GetStreamAsync上。在await that.GetStreamAsync(url);调试器消失之前,我已经对其进行了调试。消失。我尝试将其修复一天,但仍然无法正常工作。起初,我认为这是我的代理问题,但不是。然后,我尝试使用HttpRequest正常工作。

这是我的课。

public async Task<bool> RequestToApi(string response)
{
    HttpClientHandler httpClientHandler = new HttpClientHandler();
    if (_cdnResProxy.Value.Length > 0 && _cdnResPort.Value > 0)
    {
        httpClientHandler.Proxy = new WebProxy(string.Format("{0}:{1}",
        _cdnResProxy.Value,
        _cdnResPort.Value))
        { BypassProxyOnLocal = true };
    }

    //try to remove proxy here already but still not work

    using (var hClient = new HttpClient(httpClientHandler))
    {
        hClient.DefaultRequestHeaders.ExpectContinue = false;
        var result = await hClient.Get<ResponseObj>(
             $"https://www.example.com/api/somepath?something={someValue}");

        return result.success;
    }
}

public static class HttpClientExtension
{
    public static async Task<T> Get<T>(this HttpClient that, string url)
    {
        var stream = await that.GetStreamAsync(url); //stuck here
        JsonSerializer serializer = new JsonSerializer();
        T data;
        using (StreamReader streamReader = new StreamReader(stream))
        {
            data = (T)serializer.Deserialize(streamReader, typeof(T));
        }

        return data;
    }
}


这是我的控制器。

    [HttpPost]
    [SwaggerVisible]
    [SwaggerOperation("SignIn_VerifyCaptchaAction")]
    [SwaggerResponse(HttpStatusCode.OK, Type = typeof(bool))]
    public bool RecaptchaSubmit(string response)
    {
        return _service.RecaptchaSubmit(response).Result;
    }


这是我的Http软件包版本:

<package id="System.Net.Http" version="4.3.2" targetFramework="net462" />


这是我已经尝试过的方法。

var stream = await that.GetStreamAsync(url).ConfigureAwait(false);

最佳答案

由于@UltimaWeapon是正确的,因此您没有使用异步控制器,因此,所有操作均同步运行。您必须尽可能地等待所有异步调用,以避免线程阻塞。

[HttpPost]
[SwaggerVisible]
[SwaggerOperation("SignIn_VerifyCaptchaAction")]
[SwaggerResponse(HttpStatusCode.OK, Type = typeof(bool))]
public async Task<bool> RecaptchaSubmit(string response)
{
    return await _service.RecaptchaSubmit(response);
}


虽然我不知道在控制器中返回bool。通常使用AFAIK返回ActionResult。由于我不使用它,因此无法对此发表评论。

关于c# - HttpClient.GetStreamAsync卡住,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44877774/

10-12 06:44