我扩展了WebClient
类并覆盖了GetWebRequest
方法。有没有办法在此方法中为我的所有请求添加查询字符串参数?
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
HttpWebRequest webRequest = request as HttpWebRequest;
if (webRequest != null)
{
}
}
我尝试修改address
,但它似乎没有帮助。 webRequest.Address
没有制定者。
答案 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