开发者

What are WebClient's BaseAddress and QueryString properties used for?

I am trying to instantiate a WebClient as follows:

WebClient wc = new WebClient();
wc.BaseAddress = "http://contoso.com";
wc.QueryString.Add("ctNm", "some name");
wc.QueryString.Add("port", "title");
wc.QueryString.Add("rx", "1");
wc.QueryString.Add("own", "userx");
wc.QueryString.Add("asOfDt", "02/23/2011");

Since I already defined everything I need for my web request (I mean, I have BaseAddress and QueryString defined), I thought I was going to find 开发者_开发知识库some sort of method that would allow me to issue the request without passing in any additional parameters. To my surprise, all methods in WebClient (DownloadData, DownloadFile, DownloadString,OpenRead, etc.) require a Uri or a string as parameter.

What's the point in having a BaseAddress and a QueryString properties that you can add values to if you still have to construct the URL manually in order to issue the request? Am I using the wrong tool here? Should I be using WebRequest instead?


If you wanted then to access http://contoso.com/test.html with those query parameters, you could write:

wc.DownloadString("test.html");

In other words, BaseAddress and QueryString are best used when you're downloading multiple pages from the same site.

Otherwise, construct your own absolute Uri using the Uri or UriBuilder classes, and pass in the fully formed Uri to DownloadString (or whatever method you need to call).


From http://msdn.microsoft.com/en-us/library/system.net.webclient.baseaddress.aspx:

The BaseAddress property contains a base URI that is combined with a relative address. When you call a method that uploads or downloads data, the WebClient object combines this base URI with the relative address you specify in the method call. If you specify an absolute URI, WebClient does not use the BaseAddress property value.

So BaseAddress is doing the generic thing on the WebClient it is supposed to do for all methods that can be called. Multiple methods can be called after each other re-using this single one time configured web client instance.

The method itself is responsible for giving the path to its execution relative to the BaseAddress, or an absolute path overriding the pre-configured BaseAddress.

Sounds logical to me :-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜