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. Open Visual Studio IDE Click on File –> New –> Project from the menu Select “Console Application” to create a new Console Application project Save the project with a name In the solution explorer window, select the console application project you just created Right-click and select “Manage NuGet Packages” Specify “Microsoft.AspNet.WebAPI.SelfHost” in the search box of the “Manage NuGet Packages” dialog window 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. Related content how-to How to use FastEndpoints in ASP.NET Core Take advantage of the free open-source FastEndpoints library to build fast and lean APIs in your ASP.NET Core applications. By Joydip Kanjilal Jul 11, 2024 7 mins Microsoft .NET C# Development Libraries and Frameworks how-to How to use Refit to consume APIs in ASP.NET Core Take advantage of Refit REST library to simplify API consumption and make your code cleaner, more efficient, and easier to maintain. By Joydip Kanjilal Jul 04, 2024 10 mins C# Microsoft .NET Software Deployment how-to When to use an abstract class vs. interface in C# Understanding the differences between an abstract class and interface is key to designing loosely coupled and extensible applications. By Joydip Kanjilal Jun 20, 2024 10 mins Small and Medium Business Microsoft .NET C# how-to 6 security best practices for ASP.NET Core Learn the best practices and built-in safeguards for preventing attacks and protecting sensitive data in your ASP.NET Core web applications. By Joydip Kanjilal Jun 07, 2024 6 mins C# Microsoft .NET Web Development Resources Videos