Instantly share code, notes, and snippets.

What would you like to do?
C# Async HttpWebRequest Console POC
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
// Assume .NET 4.5
namespace FunAPI
class Program
static void Main(string[] args)
Console.WriteLine("This is fun");
// You can't have an async main, but these async methods want to
// propogate out to main. So main has to be smart.
// See
public static async Task HaveFun()
// There are 2 ways to use await. Here is the short way.
string json = await RequestParticipantAsync(37);
public static async Task<string> RequestParticipantAsync(int participantId)
var server = "";
var route = string.Format("/participant/{0}/", participantId);
var protocol = "https://";
var uri = protocol + server + route;
var accept = "application/json";
var auth = "ApiKey humma-numma-na:letters-and-numbers";
// See
Console.WriteLine("Request {0}", uri);
var req = (HttpWebRequest)WebRequest.Create(uri);
req.Accept = accept;
req.Headers.Add(HttpRequestHeader.Authorization, auth);
// Build the Task
// There are 2 ways to use await. Here is the long way.
Task<WebResponse> getResponseTask = req.GetResponseAsync();
// await suspends (but not blocks) this code
// See
WebResponse response = await getResponseTask;
Console.WriteLine("Content length is {0}", response.ContentLength);
Console.WriteLine("Content type is {0}", response.ContentType);
// Use the GetResponseStream to get the content
// See
Stream stream = response.GetResponseStream();
StreamReader readStream = new StreamReader(stream, Encoding.UTF8);
var content = readStream.ReadToEnd();
return content;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment