quick owin self host for web api

Pretty much laid out here: http://www.asp.net/web-api/overview/hosting-aspnet-web-api/use-owin-to-self-host-web-api. There are some errors though…

1) Create a Console App
2) Add the Microsoft.AspNet.WebApi.Core  nuget
3) Add the Microsoft.AspNet.WebApi.OwinSelfHost  nuget
4) Code

  • For the Program.cs, something like this:

    class Program
static void Main(string[] args)
string baseAddress = “http://localhost:9000/”;

// Start OWIN host
using (WebApp.Start<Startup>(url: baseAddress))
// Create HttpCient and make a request to api/values
//HttpClient client = new HttpClient();

//var response = client.GetAsync(baseAddress + “api/values”).Result;



  • Create a Startup class, something  like

    class Startup
public void Configuration(IAppBuilder appBuilder)
// Configure Web API for self-host.
HttpConfiguration config = new HttpConfiguration();
name: “DefaultApi”,
routeTemplate: “api/{controller}/{id}”,
defaults: new { id = RouteParameter.Optional }

//Browsers will generally get XML, so use the line below to get JSON in browser

//config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue(“text/html”));


  • Add a controller

    public class ValuesController : ApiController
// GET: api/Default
public async  Task<IEnumerable<string>> Get()
//await Task.Delay(5000);

return new string[] { “value1”, “value2” };

// GET: api/Default/5
public ValuesClass Get(int id)
ValuesClass vc = new ValuesClass();
vc.Name2 = “name2//diffname”;

return vc;

// POST: api/Default
public void Post([FromBody]string value)

// PUT: api/Default/5
public void Put(int id, [FromBody]string value)

// DELETE: api/Default/5
public void Delete(int id)


Note that any POCOs for data (e.g ValuesClass), you can add both XML and JSON attributes a la

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace SimpleWebService

[DataContract(Namespace = “”)]
public class ValuesClass
public ValuesClass()
Created = DateTime.Now;

public string Name { get; set; }

public string Name2 { get; set; }

public DateTime Created {get; set;}

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s