How to host Web API in a separate process
By FoxLearn 12/30/2024 3:25:20 PM 27
While IIS is a popular choice for hosting Web APIs, it's not the only option. You can host your Web API in a separate process using a host application, such as a console.
1. Create a Console Application to Host the API
To begin, we will create a console application to self-host our Web API.
- Create the Console Application: Open Visual Studio and create a new Console Application project. Name it something like "BookWebAPIHost."
- Install Required NuGet Package: Right-click on the project in Solution Explorer, select Manage NuGet Packages, search for Microsoft.AspNet.WebAPI.SelfHost, and install it. This package allows you to host your Web API without IIS.
- Write the Self-Hosting Code: In your
Program.cs
file, you can write code to host the API on a specific URL (e.g.,http://localhost:8080
):
using System; using System.Net.Http; using System.Web.Http; using System.Web.Http.SelfHost; class Program { static void Main(string[] args) { string baseAddress = "http://localhost:8080"; var config = new HttpSelfHostConfiguration(baseAddress); config.Routes.MapHttpRoute( "API Default", "api/{controller}/{id}", new { id = RouteParameter.Optional }); using (HttpSelfHostServer server = new HttpSelfHostServer(config)) { server.OpenAsync().Wait(); Console.WriteLine("Service started ... Press Enter to quit."); Console.ReadLine(); } } }
2. Create the API Model
Now let’s create a model that represents the data structure we will work with.
namespace SimpleWebAPI.Models { public class Book { public int Id { get; set; } public string Title { get; set; } public string Author { get; set; } } }
3. Create the Web API Controller
Next, create a controller that will handle the API logic. This controller will use the Book
model to return a list of books:
using System.Collections.Generic; using System.Web.Http; using SimpleWebAPI.Models; public class BooksController : ApiController { private static List<Book> books = new List<Book> { new Book { Id = 1, Title = "The Great Gatsby", Author = "F. Scott Fitzgerald" }, new Book { Id = 2, Title = "1984", Author = "George Orwell" } }; public IEnumerable<Book> GetAllBooks() { return books; } }
4. Consume the Web API
To consume the API we just created, you can create another console application.
This application will send HTTP requests to our hosted Web API and display the results.
Create the New Console Application: In Visual Studio, create another console application project named "BookWebAPIClient."
Install NuGet Packages: Add the
Microsoft.AspNet.WebAPI.Client
package to the new project, as it will help with consuming the Web API.Create the Code to Call the API: In your
Program.cs
, use theHttpClient
class to request data from the Web API:
using System; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using System.Collections.Generic; namespace BookWebAPIClient { class Program { static async Task Main(string[] args) { HttpClient client = new HttpClient(); client.BaseAddress = new Uri("http://localhost:8080/"); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = await client.GetAsync("api/books"); if (response.IsSuccessStatusCode) { var books = await response.Content.ReadAsAsync<List<Book>>(); foreach (var book in books) { Console.WriteLine("{0}: {1} by {2}", book.Id, book.Title, book.Author); } } else { Console.WriteLine("Error: {0} ({1})", (int)response.StatusCode, response.ReasonPhrase); } Console.ReadKey(); } } }
5. Run the Application
Start the Web API: First, run the BookWebAPIHost project, which will start the Web API on
http://localhost:8080
.Consume the Web API: Run the BookWebAPIClient project. This will make a request to the API, retrieve the list of books, and display them in the console.
By following these steps, you can easily self-host a Web API using a console application.
- How to Create an exception handler in ASP.NET Core 8
- Working with ActionResults in Web API
- HTTP Error 500.31 - Failed to load ASP.NET Core runtime
- ASP.NET Core Performance Optimization Tips
- Best Practices to Improve ASP.NET Core Performance
- How to Maximize Performance and Scalability in ASP.NET Core
- Improving API Performance in ASP.NET Core
- DbContext in Entity Framework Core