C# tutorials > Input/Output (I/O) and Networking > .NET Networking > Building web servers with ASP.NET Core Kestrel

Building web servers with ASP.NET Core Kestrel

This tutorial demonstrates how to build a web server using ASP.NET Core's Kestrel web server. Kestrel is a cross-platform web server for ASP.NET Core based on libuv. It's the default web server in ASP.NET Core projects and is well-suited for serving dynamic content and handling HTTP requests. We'll cover the basics of setting up a simple web server, handling requests, and configuring Kestrel options.

Setting up a New ASP.NET Core Project

First, create a new ASP.NET Core Web API project using the .NET CLI. This command creates a basic project structure including necessary files for a web application. Navigate into the newly created project directory using the `cd` command.

dotnet new webapi -n KestrelExample
cd KestrelExample

Basic Program.cs Configuration

The `Program.cs` file is the entry point of the application. The `CreateHostBuilder` method configures the host builder, specifying that Kestrel should be used as the web server and configuring the `Startup` class. The `CreateDefaultBuilder` provides default configurations including Kestrel setup.

// Program.cs
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

namespace KestrelExample
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}

Configuring the Startup Class

The `Startup.cs` file configures the application's services and request pipeline. The `ConfigureServices` method is used to add services to the dependency injection container. The `Configure` method defines how the application responds to HTTP requests. Here, we define a simple endpoint that responds with 'Hello Kestrel!' when a GET request is made to the root path ('/'). `UseRouting()` and `UseEndpoints()` are used to configure the routing middleware.

// Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace KestrelExample
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            // Add services to the container.
            //services.AddControllers(); //Not needed for a simple Kestrel example without controllers
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync("Hello Kestrel!");
                });
            });
        }
    }
}

Running the Application

Run the application from the command line using `dotnet run`. This will start the Kestrel web server, and you can access the application by navigating to `http://localhost:5000` or `https://localhost:5001` in your web browser. You should see 'Hello Kestrel!' displayed.

dotnet run

Concepts Behind the Snippet

This snippet demonstrates the fundamental steps to create a basic web server using ASP.NET Core's Kestrel. It involves configuring the host builder, setting up the request pipeline, and defining endpoints to handle HTTP requests. The application is built using a minimal configuration for clarity and demonstrates the core components needed for a web server.

Real-Life Use Case

Building a basic web server like this is the foundation for any ASP.NET Core web application. It's used in web APIs, websites, and other network applications. More complex applications will build upon this foundation by adding middleware, controllers, and data access layers to handle more sophisticated requests.

Best Practices

  • Use HTTPS: Always configure Kestrel to use HTTPS in production environments to secure communication between the client and the server.
  • Configuration: Use configuration files (e.g., `appsettings.json`) to manage settings like port numbers and other server options.
  • Logging: Implement robust logging to track application behavior and errors.
  • Security: Apply security best practices, such as input validation and authentication, to protect against vulnerabilities.

Interview Tip

Understanding how Kestrel works and how to configure it is a common interview question for ASP.NET Core developers. Be prepared to explain the roles of `Program.cs` and `Startup.cs`, the concept of middleware, and the process of handling HTTP requests.

When to Use Them

Use Kestrel as the default web server for ASP.NET Core applications. It's suitable for a wide range of scenarios, from simple web APIs to complex web applications. It excels when used with a reverse proxy like Nginx or Apache in production environments to handle load balancing, SSL termination, and other advanced features.

Memory Footprint

Kestrel is designed for high performance and efficiency, and it has a relatively small memory footprint compared to some other web servers. However, the actual memory usage will depend on the application's complexity and the number of concurrent connections.

Alternatives

While Kestrel is the recommended web server for ASP.NET Core, alternatives include:

  • IIS (Internet Information Services): Can be used with ASP.NET Core on Windows servers, often used for legacy or Windows-specific applications.
  • HttpSys: Another Windows-specific web server that leverages the HTTP.sys kernel driver.

Pros

  • Cross-Platform: Kestrel runs on Windows, macOS, and Linux.
  • High Performance: Designed for speed and scalability.
  • Easy to Configure: Straightforward configuration with ASP.NET Core.
  • Lightweight: Small memory footprint.

Cons

  • Reverse Proxy Required: Kestrel is typically deployed behind a reverse proxy in production.
  • Limited Features: Compared to full-featured web servers like IIS or Apache, Kestrel has fewer built-in features and relies on the reverse proxy for advanced functionality.

FAQ

  • What is Kestrel?

    Kestrel is a cross-platform web server for ASP.NET Core based on libuv. It is the default web server in ASP.NET Core projects.
  • Why do I need a reverse proxy with Kestrel?

    Kestrel is designed to be run behind a reverse proxy like Nginx or Apache in production. The reverse proxy handles tasks such as SSL termination, load balancing, and static file serving, allowing Kestrel to focus on handling dynamic requests efficiently.
  • How do I configure Kestrel to use HTTPS?

    You can configure Kestrel to use HTTPS in the `Program.cs` file using the `ConfigureKestrel` method. You'll need to specify the certificate to use for SSL encryption. Configuration is typically done through a configuration file (like appsettings.json) in production scenarios.