Joydip Kanjilal
Contributor

How to host your Web API in a separate process

opinion
Nov 06, 20155 mins
Software Development

Explore ways to build and host your Web API in a separate process

ASP.Net Web API is a lightweight framework used for building RESTful services that run on HTTP. RESTful services are light-weight, stateless, client-server based, cacheable services that are based on the concept of resources.

There are various ways in which you can host your Web API, and you need not always have to host your Web API in IIS. You can host it in a separate process as well. To achieve this, you would need to create a host application to host your Web API. This host application can either be a console application or even a windows application.

Creating the Web API

To get started let’s first create a console application which we would use to self-host a Web API. Once the console application has been created, you would need to add the necessary packages to host your Web API. To create the console application to build and self-host your Web API, follow these steps.

  1. Open Visual Studio IDE
  2. Click on File –> New –> Project from the menu
  3. Select “Console Application” to create a new Console Application project
  4. Save the project with a name
  5. In the solution explorer window, select the console application project you just created
  6. Right-click and select “Manage NuGet Packages”
  7. Specify “Microsoft.AspNet.WebAPI.SelfHost” in the search box of the “Manage NuGet Packages” dialog window
  8. Next, select “Microsoft.AspNet.WebAPI.SelfHost” package and click Install

This will ensure that the “Microsoft.AspNet.WebAPI.SelfHost” package is installed and that you have all the necessary references added to your project to host your Web API. The following piece of code shows how you can host a Web API that listens to port 8080.

static void Main(string[] args)

        {

            string baseAddress = "http://localhost:8080";

            var configuration = new HttpSelfHostConfiguration(baseAddress);

            configuration.Routes.MapHttpRoute(

                "API Default", "api/{controller}/{id}",

                new { id = RouteParameter.Optional });

            using (HttpSelfHostServer server = new HttpSelfHostServer(configuration))

            {

                server.OpenAsync().Wait();               

                Console.WriteLine("Service started ... Press Enter to quit.");

                Console.ReadLine();

            }

        }

In the next step, you’ll need to create a model. To do this, Add a public class named Authors and paste the following code.

namespace SimpleWebAPI.Models

{

    public class Author

    {

        public int Id { get; set; }

        public string FirstName { get; set; }

        public string LastName { get; set; }

    }

}

Now that your model class is created, let’s create a Web API controller that uses this model class to populate data and return it. To do this, add a public class named AuthorsController that extends the System.Web.Http.APIController class. The following code listing shows how you can implement a Web API controller that leverages the model we just created.

public class AuthorsController : APIController

    {

        List authors = new List

         {

            new Author { Id = 1, FirstName = “Joydip”, LastName = “Kanjilal” },

            new Author { Id = 2, FirstName = “Anand”, LastName = “Narayanaswamy”}

         };

        public List GetAllAuthors()

        {

            return authors;

        }

    }

Now that the service has been hosted, you can consume your Web API. Create another console application project to consume the Web API you created. Next, use the NuGet Package Manager to add the “Microsoft.AspNet.WebAPI.Client” package to the new console application project that you have created. As you’ll need the Author class (the model that was created in the Web API host project) to consume the Web API and display the data in the console, you can create a copy of the Author class in the new console application project that would be used to consume your Web API.

Note that the HttpClient class is a base class that is used to send and receive HTTP requests and responses. You can use the HttpClient class to make HTTP requests asynchronously.  The following piece of code shows how you can use the HttpClient class to connect to the Web API.

            HttpClient client = new HttpClient();

            client.BaseAddress = new Uri("http://localhost:8080/");

            client.DefaultRequestHeaders.Accept.Add(

                new MediaTypeWithQualityHeaderValue("application/json"));

The HttpResponseMessage class represents HttpResponse message. Here’s how you can use it to retrieve the response from a call to a Web API method.

HttpResponseMessage response = client.GetAsync("api/authors").Result;

The complete code listing that illustrates how you can consume the Web API from a console application is given below.

static void Main(string[] args)

        {

            HttpClient client = new HttpClient();

            client.BaseAddress = new Uri("http://localhost:8080/");

            client.DefaultRequestHeaders.Accept.Add(

                new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = client.GetAsync("api/authors").Result;

         if (response.IsSuccessStatusCode)

            {

                var authors = response.Content.ReadAsAsync<IList<Author>>().Result;

                foreach (var author in authors)

                {

                    Console.WriteLine("{0}t{1};t{2}", author.Id, author.FirstName, author.LastName);

                }

            }

            else

            {

                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);

            }

            Console.ReadKey();

        }

Note that we discussed one of the ways to self-host Web API in this article. You can also use OWIN to self-host your Web API. I’ll present a discussion on how you can use OWIN to self-host Web API in one of my future posts here.

Joydip Kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author