At some point, every .Net developer comes across WebRequest.Create. It’s a simple way to create any type of request to a web resource, frequently an HTTP resource. In Silverlight there is an alternate method you can use as well: WebRequest.CreateHttp. I swore until a couple minutes ago that method has existed in the full .Net framework for ages, but MSDN and Visual Studio are telling me otherwise.

Regardless, looking at the documentation for CreateHttp it appears to only support “http” or “https” requests, and returns an HttpWebRequest instead of a plain old WebRequest. To me, this seems like a convenience method: Microsoft’s developers realized the majority of the use of this class is for HTTP web requests, so why not eliminate some casting?

Unfortunately that’s not the case. Here is why it’s not the case. Given this code, should the output be the same?

Ah, if only:

image

Turns out, when you use CreateHttp, it is created with the ClientHttp browser stack. For more information on the different network stacks, see here.

Why does this matter? Well, if you are using the default behavior of Silverlight (browser stack), rely on cookies of any sort (session, authentication, etc) and create a web request to your server manually that needs those cookies (again, for authentication, session, etc), any web requests created via CreateHttp will not pass your cookies to the server. Authentication won’t work, you won’t have the same session you do if you use RIA, WCF or WebRequest.Create.

This recently came up at one of my clients. The Silverlight application uses both Windows authentication and Forms authentication to log in (both handled from within the application itself with a backing website and Membership provider). The first step is to try to auto-login the user with a WebRequest.Create to the page that forces Windows authentication (the whole site can’t require Windows auth as we have to support external users as well). If that succeeds a FormsAuthentication ticket is passed back to the client in the form of a cookie. The problem here is, we’re using the browser HTTP stack (on purpose) but I was using CreateHttp to create the WebRequest (because it felt like a convenience method). By using CreateHttp, none of my cookies created inside the Windows authentication page were being used by my WCF or RIA service calls (that were using the BrowserHttp stack). Simply switching to the Create method shared all my cookies across WCF, RIA and WebRequests.