简体   繁体   English

向WebClient发出的所有请求添加querystring参数

[英]Adding a querystring parameter to all request made by a WebClient

I have extended the WebClient class and overriden the GetWebRequest method. 我扩展了WebClient类并重写了GetWebRequest方法。 Is there any way to add a querystring parameter to all my requests in this method? 有什么方法可以在此方法中向我的所有请求添加querystring参数?

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. 我尝试修改address但似乎无济于事。 And the webRequest.Address has no setter. 而且webRequest.Address没有设置器。

I tried your sample and was able to modify the address in the GetWebRequest method by passing a new Uri to base.GetWebRequest() : 我尝试了您的示例,并能够通过将新的Uri传递给base.GetWebRequest()来修改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 然后,如果我调用new CustomWebClient().DownloadData("http://stackoverflow.com")则实际网址(如提琴手所见)为https://stackoverflow.com/?MyCustomParam=value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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