简体   繁体   中英

Adding a querystring parameter to all request made by a WebClient

I have extended the WebClient class and overriden the GetWebRequest method. Is there any way to add a querystring parameter to all my requests in this method?

protected override WebRequest GetWebRequest(Uri address)
{
    WebRequest request = base.GetWebRequest(address);

    HttpWebRequest webRequest = request as HttpWebRequest;

    if (webRequest != null)
    {

    }
}

I've tried modifying the address but it doesn't seem to help. And the webRequest.Address has no setter.

I tried your sample and was able to modify the address in the GetWebRequest method by passing a new Uri to base.GetWebRequest() :

public class CustomWebClient : WebClient
{
    protected override WebRequest GetWebRequest(Uri address)
    {
        var newUrl = address.OriginalString;

        if (newUrl.Contains("?"))
            newUrl += "&";
        else
            newUrl += "?";

        newUrl += "MyCustomParam=value";


        return base.GetWebRequest(new Uri(newUrl));
    }
}

Then if I call new CustomWebClient().DownloadData("http://stackoverflow.com") the actual url (as seen by fiddler) is https://stackoverflow.com/?MyCustomParam=value

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