Skip to content

Instantly share code, notes, and snippets.

@joeriks
Created September 20, 2013 08:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joeriks/6634580 to your computer and use it in GitHub Desktop.
Save joeriks/6634580 to your computer and use it in GitHub Desktop.
One file simple usage WebApi selfhost (console program + Microsoft.AspNet.WebApi.SelfHost nuget). Needs to be run as admin.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http.SelfHost;
using System.Web.Http;
namespace ConsoleApplication1
{
// listens to /api/foo/{id}
public class FooController : System.Web.Http.ApiController
{
public string Get(int id)
{
return "Foo " + id;
}
}
class Program
{
static void Main(string[] args)
{
var config = new HttpSelfHostConfiguration("http://localhost:8087");
config.Routes.MapHttpRoute(
"API Default", "api/{controller}/{id}",
new { id = RouteParameter.Optional });
using (HttpSelfHostServer server = new HttpSelfHostServer(config))
{
server.OpenAsync().Wait();
Console.WriteLine("Press Enter to quit.");
Console.ReadLine();
}
}
}
}
@nzbart
Copy link

nzbart commented Oct 22, 2015

Thanks for the code.

If you want to run a self-hosted API without admin permissions, for example when running a test, use the following:

var config = new HttpSelfHostConfiguration("http://localhost:80/Temporary_Listen_Addresses/Demo");

And access it via http://localhost/Temporary_Listen_Addresses/Demo/api/Foo/42.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment