我在webclient类中发现了一个奇怪的行为。当我使用UploadValues()同步方法时,我会正常获取响应uri,但是当我对相同的URL使用异步版本UploadValuesTaskAsync()时,它将返回响应uri为null。为什么?

例:

using (var client = new CustomWebClient())
{
    await Get(client);
    Get(client);
}

private async Task GetAsync(WebClient client)
{
      var resAsync = await client.UploadValuesTaskAsync("http://address.com", requestData);
      //client.ResponseUri null here
}

private void Get(WebClient client)
{
    var res= client.UploadValues("http://address.com", requestData);
     //client.ResponseUri **not** null here
}


GetAsync方法中,client.ResponseUri为null,而对于UploadValues,则不为null。

编辑:

我发现WebClient是“定制的”:

所以该类是:

 public class CustomWebClient : WebClient
 {
    public CookieContainer Cookies { get; private set; }
    public Uri ResponseUri { get; private set; }

    public CustomWebClient()
    {
        Cookies = new CookieContainer();
    }

    protected override WebRequest GetWebRequest(Uri address)
    {
        var request = base.GetWebRequest(address) as HttpWebRequest;
        if (request == null)
        {
            return base.GetWebRequest(address);
        }
        request.CookieContainer = Cookies;
        return request;
    }

    protected override WebResponse GetWebResponse(WebRequest request)
    {
        var response = base.GetWebResponse(request);
        ResponseUri = response.ResponseUri;
        return response;
    }
}


我检查了在synchronous方法中是否击中GetWebResponse方法,然后继续下一行。但是在asynchronous版本中,它永远不会命中GetWebResponse

最佳答案

您的自定义类仅覆盖同步WebResponse GetWebResponse(WebRequest request)方法的行为。

您需要为异步版本添加替代:

 protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult result)
 {
     var response = base.GetWebResponse(request, result);
     ResponseUri = response.ResponseUri;
     return response;
 }

09-13 01:42