Search icon CANCEL
Subscription
0
Cart icon
Cart
Close icon
You have no products in your basket yet
Save more on your purchases!
Savings automatically calculated. No voucher code required
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Customizing ASP.NET Core 6.0 - Second Edition

You're reading from  Customizing ASP.NET Core 6.0 - Second Edition

Product type Book
Published in Dec 2021
Publisher Packt
ISBN-13 9781803233604
Pages 204 pages
Edition 2nd Edition
Languages
Author (1):
Jürgen Gutsch Jürgen Gutsch
Profile icon Jürgen Gutsch
Toc

Table of Contents (18) Chapters close

Preface 1. Chapter 1: Customizing Logging 2. Chapter 2: Customizing App Configuration 3. Chapter 3: Customizing Dependency Injection 4. Chapter 4: Configuring and Customizing HTTPS with Kestrel 5. Chapter 5: Configuring WebHostBuilder 6. Chapter 6: Using Different Hosting Models 7. Chapter 7: Using IHostedService and BackgroundService 8. Chapter 8: Writing Custom Middleware 9. Chapter 9: Working with Endpoint Routing 10. Chapter 10: Customizing ASP.NET Core Identity 11. Chapter 11: Configuring Identity Management 12. Chapter 12: Content Negotiation Using a Custom OutputFormatter 13. Chapter 13: Managing Inputs with Custom ModelBinder 14. Chapter 14: Creating a Custom ActionFilter 15. Chapter 15: Working with Caches 16. Chapter 16: Creating Custom TagHelper 17. Other Books You May Enjoy

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.

You have been reading a chapter from
Customizing ASP.NET Core 6.0 - Second Edition
Published in: Dec 2021 Publisher: Packt ISBN-13: 9781803233604
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}