Corrado's Blog 2.0

Online thoughts of a technology funatic

Exception deriving from WebClient on Windows Phone 7.5

I was working on a Windows Phone 7.5 app that requires to use WebClient class to post a HEAD request to the server, since WebClient doesn’t support it, i used the trick to derive from WebClient and override the GetWebRequest method.

public class WebClientEx : WebClient
        {            
            public WebClientEx()
            {
            }
            
            public string Method
            {
                get;
                set;
            }

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

                if (!string.IsNullOrEmpty(Method))
                    webRequest.Method = Method;

                return webRequest;
            }
        }

i then used the new class this way:

WebClientEx client = new WebClientEx() { Method = "HEAD" };
client.DownloadStringCompleted += (s, e) => ...
client.DownloadStringAsync(new Uri(uri, UriKind.Absolute));

Nothing new indeed, so what is the reason of this post? the fact that everything was fine in Windows Phone 8 but it was failing with a “inheritance security rules violated by type WebClientEx. Derived types must either  match the security accessibility of the base type or be less accessible.  If the base class has a non-transparent default constructor, the derived class must also have a default constructor, and the method inheritance rules apply across those two methods.”  when run on a Windows Phone 7.5 device.

A quick search and it looks like that the reason comes from a missing attribute applied to derived class constructor.

Adding a default constructor marked with SecuritySafeCritical attribute solved it (Phew!)

[System.Security.SecuritySafeCritical]
public WebClientEx()
{
}