简体   繁体   中英

Webclient not getting response uri

I found a strange behaviour in the webclient class. When i use the UploadValues() synchronous method i get the response uri normally, but when i use the async version UploadValuesTaskAsync() to the same url it returns the response uri as null. Why?

Example:

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
}

In the GetAsync method the client.ResponseUri comes null, and not null for the UploadValues .

EDIT:

I discovered the WebClient is "customized":

so the class is:

 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;
    }
}

I checked that in the synchronous method it hits the GetWebResponse method before continous to the next line. But in the asynchronous version it not hit the GetWebResponse never.

Your customized class is only overriding the behavior for the synchronous WebResponse GetWebResponse(WebRequest request) method.

You need to add an override for the async version:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM