The other day I got frustrated that I couldn’t find a code example of a simple .NET OWIN standalone (i.e. not using IIS) web server (i.e. not a REST server) for .NET. After some research and trial-and-horror I came up with the following:
using System; using System.Diagnostics; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web.Http.SelfHost; namespace WebServer { class Program { static void Main(string[] args) { const string serviceBaseUri = "http://localhost:4578/"; var config = new HttpSelfHostConfiguration(serviceBaseUri); using (var server = new HttpSelfHostServer(config, new MyMessageHandler())) { server.OpenAsync().Wait(); Console.WriteLine("Press Ctrl+C to quit."); Console.ReadLine(); } } } public class MyMessageHandler : HttpMessageHandler { protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { Debug.Print(request.ToString()); var res = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("Hello, World!") }; var tsc = new TaskCompletionSource<HttpResponseMessage>(); tsc.SetResult(res); // Also sets the task state to "RanToCompletion" return tsc.Task; } } }
Enjoy!