Search code examples
c#.netasynchronousportable-class-library

How can I use System.Net.HttpWebRequest with async/await?


I've been trying to write a simple HTTP client as a Portable Class Library with minimum dependencies, which made me think that I should use System.Net.HttpWebRequest.

I've looked at the documentation, but it shows only GetResponse/GetResponseStream methods, which I don't have in my implementation. I only have BeginGetResponse, BeginGetResponseStream, etc. I've tried using Task.Factory.FromAsync to convert this to a Task, but that only returns a Task, not a Task<HttpWebResponse>.

Is the correct approach here to use a cast, such as the following?

var response = (Task<HttpWebResponse>)Task.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse);

Or am I missing something?

edit: I don't want to introduce dependencies on additional NuGet packages, since all I need to do is a single HTTP request in one place in a tiny library.


Solution

  • If you use a generic Task<>.Factory you get a little more type-safety:

    var request = WebRequest.CreateHttp("https://www.google.com");
    object state = null; // or whatever state you want.
    var task = Task<WebResponse>.Factory.FromAsync(
        request.BeginGetResponse,
        request.EndGetResponse, 
        state);
    

    However, as with when you're not doing async calls, if you want an HttpWebResponse rather than just a WebResponse, you'll need to do an additional cast. And be sure to close/dispose your response:

    using (var response = (HttpWebResponse) (await task))
    {
        // use response
    }