Quantcast
Viewing all articles
Browse latest Browse all 16

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 may be NSFW.
Clik here to view.
image

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


Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.

Viewing all articles
Browse latest Browse all 16

Trending Articles