Book Image

Customizing ASP.NET Core 6.0 - Second Edition

By : Jürgen Gutsch
Book Image

Customizing ASP.NET Core 6.0 - Second Edition

By: Jürgen Gutsch

Overview of this book

ASP.NET Core is packed full of hidden features for building sophisticated web applications – but if you don’t know how to customize it, you’re not making the most of its capabilities. Customizing ASP.NET Core 6.0 is a book that will teach you all about tweaking the knobs at various layers and take experienced programmers’ skills to a new level. This updated second edition covers the latest features and changes in the .NET 6 LTS version, along with new insights and customization techniques for important topics such as authentication and authorization. You’ll also learn how to work with caches and change the default behavior of ASP.NET Core apps. This book will show you the essential concepts relating to tweaking the framework, such as configuration, dependency injection, routing, action filters, and more. As you progress, you'll be able to create custom solutions that meet the needs of your use case with ASP.NET Core. Later chapters will cover expert techniques and best practices for using the framework for your app development needs, from UI design to hosting. Finally, you'll focus on the new endpoint routing in ASP.NET Core to build custom endpoints and add third-party endpoints to your web apps for processing requests faster. By the end of this book, you'll be able to customize ASP.NET Core to develop better, more robust apps.
Table of Contents (18 chapters)

Configuring the configuration

Let's start by looking at how to configure your various configuration options.

Since ASP.NET Core 2.0, the configuration is hidden in the default configuration of WebHostBuilder and is no longer part of Startup.cs. This helps to keep the startup clean and simple.

In ASP.NET Core 3.1 up to ASP.NET Core 5.0, the code looks like this:

// ASP.NET Core 3.0 and later
public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }
    public static IHostBuilder CreateHostBuilder(string[] 
      args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            }
}

In ASP.NET Core 6.0, Microsoft introduced the minimal application programming interface (API) approach that simplifies the configuration a lot. This doesn't use Startup and adds all the configuration in the Program.cs file. Let's see how it looks here:

Var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
// The rest of the file isn't relevant for this chapter

Fortunately, in both versions, you are also able to override the default settings to customize the configuration in the way you need it. In both versions, we extend IWebHostBuilder with the ConfigureAppConfiguration() method where the magic will happen.

This is what the configuration looks like in ASP.NET Core 3.1 and ASP.NET Core 5.0:

Host.CreateDefaultBuilder(args)
    .ConfigureWebHostDefaults(webBuilder =>
    {
        webBuilder
          .ConfigureAppConfiguration((builderContext,
            config) =>
        {
            // configure configuration here
        })
        .UseStartup<Startup>();
    });

This is what the code looks like when using the minimal API approach. You also can use ConfigureAppConfiguration to configure the app configuration:

builder.WebHost.ConfigureAppConfiguration((builderContext, config) =>
{
    // configure configuration here
});

But there is a much simpler approach, by accessing the Configuration property of the builder:

builder.Configuration.AddJsonFile(
     "appsettings.json",
     optional: false,
     reloadOnChange: true);

When you create a new ASP.NET Core project, you will already have appsettings.json and appsettings.Development.json configured. You can, and should, use these configuration files to configure your app; this is the preconfigured way, and most ASP.NET Core developers will look for an appsettings.json file to configure the application. This is absolutely fine and works pretty well.

The following code snippet shows the encapsulated default configuration to read the appsettings.json files:

var env = builder.Environment;
builder.Configuration.SetBasePath(env.ContentRootPath);
builder.Configuration.AddJsonFile(
    "appsettings.json", 
    optional: false, 
    reloadOnChange: true);
builder.Configuration.AddJsonFile(
    $"appsettings.{env.EnvironmentName}.json", 
    optional: true, 
    reloadOnChange: true);
builder.Configuration.AddEnvironmentVariables();

This configuration also sets the base path of the application and adds the configuration via environment variables.

Whenever you customize the application configuration, you should add the configuration via environment variables as a final step, using the AddEnvironmentVariables() method. The order of the configuration matters and the configuration providers that you add later on will override the configurations added previously. Be sure that the environment variables always override the configurations that are set via a file. This way, you also ensure that the configuration of your application on an Azure App Service will be passed to the application as environment variables.

IConfigurationBuilder has a lot of extension methods to add more configurations, such as XML or INI configuration files and in-memory configurations. You can find additional configuration providers built by the community to read in YAML files, database values, and a lot more. In an upcoming section, we will see how to read INI files. First, we will look at using typed configurations.