Skip to content

Instantly share code, notes, and snippets.

@chgeuer
Created February 28, 2012 18:28
Show Gist options
  • Save chgeuer/1934157 to your computer and use it in GitHub Desktop.
Save chgeuer/1934157 to your computer and use it in GitHub Desktop.
Sample for self-hosting ASP.NET Web API
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.SelfHost;
using System.Threading;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
var baseAddress = "http://localhost:8080/";
var config = new HttpSelfHostConfiguration(baseAddress);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
using (HttpSelfHostServer server = new HttpSelfHostServer(config))
{
server.OpenAsync().Wait();
HttpClientHandler httpClientHandler = new HttpClientHandler();
httpClientHandler.CookieContainer = new CookieContainer();
httpClientHandler.CookieContainer.Add(new Cookie("name", "value", "/", "google.de"));
var client = new HttpClient(httpClientHandler) { BaseAddress = new Uri(/*"http://www.google.de/") }; */ baseAddress) };
var request = new HttpRequestMessage(HttpMethod.Get, "api/hello");
Console.WriteLine("Client received: {0}",
client.SendAsync(request).Result.Content.ReadAsStringAsync().Result); // client.GetStringAsync("api/hello").Result);
}
}
}
public class HelloController : ApiController
{
public string Get()
{
return "Hello, world!";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment