Skip to content

Instantly share code, notes, and snippets.

@tugberkugurlu
Created July 3, 2013 09:50
Show Gist options
  • Save tugberkugurlu/5916721 to your computer and use it in GitHub Desktop.
Save tugberkugurlu/5916721 to your computer and use it in GitHub Desktop.
This sample demonstrates the in-memory hosting of an ASP.NET Web API application.
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
namespace WebApiInMemoryHost
{
class Program
{
static void Main(string[] args)
{
RunAsync();
}
private static async Task RunAsync()
{
HttpConfiguration config = new HttpConfiguration();
config.Routes.MapHttpRoute("DefaultHttpRoute", "api/{controller}");
using (HttpServer httpServer = new HttpServer(config))
using (HttpClient httpClient = new HttpClient(httpServer, false))
{
Console.WriteLine("Started the server!");
while (!Console.ReadLine().Equals("q", StringComparison.InvariantCultureIgnoreCase))
{
Console.WriteLine("Sending the request...");
HttpResponseMessage response = await httpClient.GetAsync("http://host/api/cars");
string[] cars = await response.Content.ReadAsAsync<string[]>();
foreach (string car in cars)
{
Console.WriteLine(car);
}
Console.WriteLine("Done!");
}
}
Console.WriteLine("Closed the server!");
}
}
public class CarsController : ApiController
{
public string[] GetCars()
{
return new[]
{
"Car 1",
"Car 2",
"Car 3"
};
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment