将querystring参数添加到WebClient发出的所有请求中

时间:2014-11-30 23:58:21

标签: c#

我扩展了WebClient类并覆盖了GetWebRequest方法。有没有办法在此方法中为我的所有请求添加查询字符串参数?

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

    HttpWebRequest webRequest = request as HttpWebRequest;

    if (webRequest != null)
    {

    }
}

我尝试修改address,但它似乎没有帮助。 webRequest.Address没有制定者。

1 个答案:

答案 0 :(得分:1)

我尝试了您的示例,并通过将新GetWebRequest传递给Uri来修改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));
    }
}

然后,如果我拨打new CustomWebClient().DownloadData("http://stackoverflow.com"),实际网址(由fiddler看到)为https://stackoverflow.com/?MyCustomParam=value