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 14 great preprocessors for developers who love to code Sometimes it seems like the rules of programming are designed to make coding a chore. Here are 14 ways preprocessors can help make software development fun again. By Peter Wayner Nov 18, 2024 10 mins Development Tools Software Development feature Designing the APIs that accidentally power businesses Well-designed APIs, even those often-neglected internal APIs, make developers more productive and businesses more agile. By Jean Yang Nov 18, 2024 6 mins APIs Software Development news Spin 3.0 supports polyglot development using Wasm components Fermyon’s open source framework for building server-side WebAssembly apps allows developers to compose apps from components created with different languages. By Paul Krill Nov 18, 2024 2 mins Microservices Serverless Computing Development Libraries and Frameworks news Go language evolving for future hardware, AI workloads The Go team is working to adapt Go to large multicore systems, the latest hardware instructions, and the needs of developers of large-scale AI systems. By Paul Krill Nov 15, 2024 3 mins Google Go Generative AI Programming Languages Resources Videos