Self-hosting ASP.NET Web API

Just a simple example, showing how to self-host ASP.NET Web API.

    1. On an elevated console (“Run as administrator”), execute “netsh http add urlacl url=http://+:8080/ user=<your user name>”, to allow the running user to listen on port 8080.
    2. On Visual Studio, create a “Console Application” project.
    3. Change the project’s Target Framework property from “.NET Framework 4 Client Profile” to “.NET Framework 4 profile”.
    4. Install the AspNetWebApi.Selfhost NuGet package
    5. Create a public ApiController derived class.
public class HelloController : ApiController
{
  public HttpResponseMessage Get()
  {
    return new HttpResponseMessage
        {
          Content = new StringContent("Hello HTTP")
        };
  }
}
    1. In the program’s Main method,
      1. Create a HttpSelfHostConfiguration, initialized with the base address.
      2. Add the default route: MapHttpRoute(“default”, “{controller}/{id}”, new { id = RouteParameter.Optional });
      3. Create a HttpSelfHostServer, initialized with the above configuration object.
      4. Open the server, bearing in mind that the OpenAsync method is asynchronous.
static void Main(string[] args)
{
  var config = new HttpSelfHostConfiguration("http://localhost:8080");
  config.Routes.MapHttpRoute("default", "{controller}/{id}", new { id = RouteParameter.Optional });
  var server = new HttpSelfHostServer(config);
  server.OpenAsync().Wait();

  Console.WriteLine("Server is opened");
  Console.ReadKey();

  1. Run the program, open a browser and access http://localhost:8080/hello.

image

That’s it. You now have a self-hosted ASP.NET Web API server.

Advertisements

10 thoughts on “Self-hosting ASP.NET Web API

  1. g

    Hi Pedro,

    I take it I could run the app As a windows service instead of a console app? Also if I was to deploy this on the server, all I would do is need to change the httpselfhostconfiguration(“http://localhost:8080”) to the URL which is pointing at the server?

    Many thanks

    Reply
    1. pedrofelix Post author

      1) Yes, you could run as a windows service.

      2) What do you mean by “deploy on the server”? Is it on top of IIS? If so, you don’t use HttpSelfHostConfiguration.

      Reply
      1. g

        Thanks for the quick reply!

        On a production server you add the url’s address to the host headers of a website in iis, how would i wire up the web API to capture the http requests to a given domain which is pointing at that server, change the value passed through httpselfhostconfiguration?.

        Yes your correct not onto of iis.

      2. pedrofelix Post author

        From my observations, the host name of the address that you pass to the HttpSelfHostConfiguration ctor is ignored.

  2. Bill Hensley

    I’ve tried to follow the steps you outlined and I get a 404 with the error “No type was found that matches the controller named ‘hello'”. I’m sure I’m making some very simple mistake. Any ideas? Thanks!

    Reply
    1. pedrofelix Post author

      Is the HelloController class public? Is it in the same assembly? Is HelloController a nested class?

      Reply
  3. Pingback: Web API References | It doesn't have to be Geeky

    1. Darshana

      Make sure you include the reference in you project!
      You can add it via C:\windows\microsoft .net\framework\v4.0.30319\ directory

      Reply

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