Using WebClient in SharePoint context

Recently while working on one of my projects I needed to use the WebClient in order to obtain a rendered version of a Publishing Page using a url. My environment consisted of an Publishing Site using Active Directory authentication and it's extend equivalent using Anonymous Access as well. My goal was to obtain the rendered page before it's published to be able to check the standards compliance of the rendered code.

As I have coded the most basic piece of WebClient usage:

byte[] response;  
using (WebClient wc = new WebClient())  
{
  wc.UseDefaultCredentials = true;
  response =
    wc.DownloadData("http://SharePoint/Pages/default.aspx");
}

I have discovered I've received from the response the rendered version of the published version (1.0) instead of the current minor version (1.1). As I've been logged in using valid credentials and I've configured the WebClient instance to use default credentials I couldn't figure out the reason of this behavior.

After a while trying some other approaches out I have noticed I've been using the Site Collection using Anonymous Access. After changing it to the editors Site Collection (the one without AD authentication only) I have finally retrieved the major version of the page. It turned out that whenever possible the WebClient will try to make the request without any authentication. It will use the credentials only if asked by the server - what will never happen by the way if the anonymous access is turned on.

I think it's definitely something you should remember if you work with the WebClient within SharePoint. WebClient is a very useful feature still it might just spare you some precious minutes trying to figure out why it doesn't work as you would expect it to.

Comments

comments powered by Disqus