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 feature What is Rust? Safe, fast, and easy software development Unlike most programming languages, Rust doesn't make you choose between speed, safety, and ease of use. Find out how Rust delivers better code with fewer compromises, and a few downsides to consider before learning Rust. By Serdar Yegulalp Nov 20, 2024 11 mins Rust Programming Languages Software Development how-to Kotlin for Java developers: Classes and coroutines Kotlin was designed to bring more flexibility and flow to programming in the JVM. Here's an in-depth look at how Kotlin makes working with classes and objects easier and introduces coroutines to modernize concurrency. By Matthew Tyson Nov 20, 2024 9 mins Java Kotlin Programming Languages analysis Azure AI Foundry tools for changes in AI applications Microsoft’s launch of Azure AI Foundry at Ignite 2024 signals a welcome shift from chatbots to agents and to using AI for business process automation. By Simon Bisson Nov 20, 2024 7 mins Microsoft Azure Generative AI Development Tools news Microsoft unveils imaging APIs for Windows Copilot Runtime Generative AI-backed APIs will allow developers to build image super resolution, image segmentation, object erase, and OCR capabilities into Windows applications. By Paul Krill Nov 19, 2024 2 mins Generative AI APIs Development Libraries and Frameworks Resources Videos