Showing posts from January, 2013

Calling HttpClient async functions from constructors in ASP.NET 4.5

Recently, we have been using async/await a lot in our ASP.NET MVC project. It is very powerful. However, as with most power, comes great responsibility. In multithreading, this adage can be translated to "with great parallelism, don't deadlock" . As it has been documented and explained, in the current ASP.NET stack, when you await during a request, you will get a callback on the originating thread (that's the point of await/async after all). When you make an awaitable call to let's say HttpClient.GetStringAsync() , it will want to come back on that thread also. As well explained by Stephen Cleary in his StackOverflow answer ( here ), this goes south pretty much immediately if you start blocking somewhere in the call stack. This is true if you call a Task<T>.Result . No async in constructors Unfortunately, for good reasons, constructors cannot be async. Therefore, they cannot await on anything. In our case, we needed to retrieve some data from another

HttpClient, Basic authentication and Bing

On Friday, I was trying to use the Bing API to test an issue we were having while using .NET 4.5, LINQ and async/await patterns. While Bing recommends you use their .NET library , I needed to keep my example as a pure core libraries example so people could try to reproduce my issue without having to download any third party library. The Bing API offers Basic authentication or OAuth (to keep track of how much your are using of your monthly quota). So, I had to make a remote call to a web service using Basic authentication (to keep it simple). In .NET 4.5, the recommended way tot access remote resources is to use HttpClient . I spent a fair bit of time researching this online and either it is so simple or nobody ever tried, but bottom line was that nobody has a clear and simple example There are several key elements to a successful Bing query using HttpClient. Header info According to the RFC 2617 , basic authentication information is passed as an HTTP header. Fortunately, the Htt