Self host web API

In this post, I will show you how to create a web API that runs outside the IIS application.
Open visual studio and create a console application

Self host web API

Add the Web API and OWIN Packages

From the Tools menu, click Library Package Manager, then click Package Manager Console. In the Package Manager Console window, enter the following command:

`Install-Package Microsoft.AspNet.WebApi.OwinSelfHost`  

image

Right click the project and add new class named Startup.cs and add following code snippet in it

public class Startup 
    { 
        // This code configures Web API. The Startup class is specified as a type
        // parameter in the WebApp.Start method.
        public void Configuration(IAppBuilder appBuilder) 
        { 
            // Configure Web API for self-host. 
            HttpConfiguration config = new HttpConfiguration(); 
            config.Routes.MapHttpRoute( 
                name: "DefaultApi", 
                routeTemplate: "api/{controller}/{id}", 
                defaults: new { id = RouteParameter.Optional } 
            ); 

            appBuilder.UseWebApi(config); 
        } 
    } 

Next, add a Web API controller class. In Solution Explorer, right click the project and select Add / Class to add a new class named HelloController and add following code snippet

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;

namespace SelfHostWebApi
{
    public class HelloController : ApiController
    {
        // GET api/values/5 
        public string Get(int id)
        {
            return "Hello API";
        }
    }
}

Open Program.cs and add following code inside main method

using Microsoft.Owin.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace SelfHostWebApi
{
    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/hello").Result;

                Console.WriteLine(response);
                Console.WriteLine(response.Content.ReadAsStringAsync().Result);
            }

            Console.ReadLine();
        }
    }
}

Your self hosted web API is ready. When you run the application you will see the following output if everything works fine


Self host web API

Please do not post any spam link in the comment box😊

Post a Comment (0)
Previous Post Next Post