Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Customizing ASP.NET Core 6.0
Customizing ASP.NET Core 6.0

Customizing ASP.NET Core 6.0: Learn to turn the right screws to optimize ASP.NET Core applications for better performance , Second Edition

Arrow left icon
Profile Icon Jürgen Gutsch
Arrow right icon
Mex$179.99 Mex$541.99
Full star icon Full star icon Full star icon Full star icon Empty star icon 4 (6 Ratings)
eBook Dec 2021 204 pages 2nd Edition
eBook
Mex$179.99 Mex$541.99
Paperback
Mex$676.99
Subscription
Free Trial
Arrow left icon
Profile Icon Jürgen Gutsch
Arrow right icon
Mex$179.99 Mex$541.99
Full star icon Full star icon Full star icon Full star icon Empty star icon 4 (6 Ratings)
eBook Dec 2021 204 pages 2nd Edition
eBook
Mex$179.99 Mex$541.99
Paperback
Mex$676.99
Subscription
Free Trial
eBook
Mex$179.99 Mex$541.99
Paperback
Mex$676.99
Subscription
Free Trial

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Customizing ASP.NET Core 6.0

Chapter 2: Customizing App Configuration

This second chapter is about application configuration, how to use it, and how to customize the ASP.NET configuration to employ different ways to configure your app. Perhaps you already have an existing Extensible Markup Language (XML) configuration or want to share a YAML Ain't Markup Language (YAML) configuration file over different kinds of applications. Sometimes, it also makes sense to read configuration values out of a database.

In this chapter, we will be covering the following topics:

  • Configuring the configuration
  • Using typed configurations
  • Configuration using Initialization (INI) files
  • Configuration providers

The topics in this chapter refer to the hosting layer of the ASP.NET Core architecture:

Figure 2.1 – ASP.NET Core architecture

Figure 2.1 – ASP.NET Core architecture

Technical requirements

To follow the descriptions in this chapter, you will need to create an ASP.NET Core Model-View-Controller (MVC) application. Open your console, shell, or Bash terminal, and change to your working directory. Use the following command to create a new MVC application:

dotnet new mvc -n ConfigureSample -o ConfigureSample

Now, open the project in Visual Studio by double-clicking the project file or, in Visual Studio Code (VS Code), by typing the following command in the already open console:

cd ConfigureSample
code .

All of the code samples in this chapter can be found in the GitHub repository for this book at https://github.com/PacktPublishing/Customizing-ASP.NET-Core-6.0-Second-Edition/tree/main/Chapter02.

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.

Using typed configurations

Before trying to read INI files, it makes sense for you to see how to use typed configurations instead of reading the configuration via IConfiguration, key by key.

To read a typed configuration, you need to define the type to configure. I usually create a class called AppSettings, as follows:

namespace ConfigureSample;
public class AppSettings
{
    public int Foo { get; set; }
    public string Bar { get; set; }
}

This is a simple Plain Old CLR Object (POCO) class that will only contain the application setting values, as illustrated in the following code snippet. These classes can then be filled with specific configuration sections inside the ConfigureServices method in Startup.cs until ASP.NET Core 5.0:

services.Configure<AppSettings>
   (Configuration.GetSection("AppSettings"));

Using the minimal API approach, you need to configure the AppSettings class, like this:

builder.Services.Configure<AppSettings>(
    builder.Configuration.GetSection("AppSettings"));

This way, the typed configuration also gets registered as a service in the dependency injection (DI) container and can be used everywhere in the application. You are able to create different configuration types for each configuration section. In most cases, one section should be fine, but sometimes it makes sense to divide the settings into different sections. The next snippet shows how to use the configuration in an MVC controller:

using Microsoft.Extensions.Options;
// ...
public class HomeController : Controller
{
    private readonly AppSettings _options;
    public HomeController(IOptions<AppSettings> options)
    {
        _options = options.Value;
    }
    public IActionResult Index()
    {
        ViewData["Message"] = _options.Bar;
        return View();
    }

IOptions<AppSettings> is a wrapper around our AppSettings type, and the Value property contains the actual instance of AppSettings, including the values from the configuration file.

To try reading the settings in, the appsettings.json file needs to have the AppSettings section configured, otherwise the values are null or not set. Let's now add the section to the appsettings.json file, as follows:

{
    "Logging": {
        "LogLevel": {
            "Default": "Warning"
        }
    },
    "AllowedHosts": "*",
    "AppSettings": {
        "Foo": 123,
        "Bar": "Bar"
    }
}

Next, we'll examine how INI files can be used for configuration.

Configuration using INI files

To also use INI files to configure the application, you will need to add the INI configuration inside the ConfigureAppConfiguration() method in Program.cs, as follows:

builder.Configuration.AddIniFile(
    "appsettings.ini", 
    optional: false, 
    reloadOnChange: true);
builder.Configuration.AddJsonFile(
    $"appsettings.{env.EnvironmentName}.ini", 
    optional: true, 
    reloadOnChange: true);

This code loads the INI files the same way as the JavaScript Object Notation (JSON) configuration files. The first line is a required configuration, and the second line is an optional configuration depending on the current runtime environment.

The INI file could look like this:

[AppSettings]
Bar="FooBar"

As you can see, this file contains a section called AppSettings and a property called Bar.

Earlier, we said that the order of the configuration matters. If you add the two lines to configure via INI files after the configuration via JSON files, the INI files will override the settings from the JSON files. The Bar property gets overridden with "FooBar" and the Foo property stays the same because it will not be overridden. Also, the values out of the INI file will be available via the typed configuration created previously.

Every other configuration provider will work the same way. Let's now see how a configuration provider will look.

Configuration providers

A configuration provider is an implementation of IConfigurationProvider that is created by a configuration source, which is an implementation of IConfigurationSource. The configuration provider then reads the data from somewhere and provides it via Dictionary.

To add a custom or third-party configuration provider to ASP.NET Core, you will need to call the Add method on ConfigurationBuilder and insert the configuration source. This is just an example:

// add new configuration source
builder.Configuration.Add(new MyCustomConfigurationSource
{
    SourceConfig = //configure whatever source
    Optional = false,
    ReloadOnChange = true
});

Usually, you would create an extension method to add the configuration source more easily, as illustrated here:

builder.Configuration.AddMyCustomSource("source", optional: false, reloadOnChange: true);

A really detailed concrete example about how to create a custom configuration provider has been written by Andrew Lock. You can find this in the Further reading section of this chapter.

Summary

In most cases, you will not need to add a different configuration provider or create your own configuration provider, but it's good to know how to change it, just in case. Also, using a typed configuration is a nice way to read and provide the settings. In classic ASP.NET, we used a manually created façade to read the application settings in a typed manner. Now, this is automatically done by just providing a type. This type will be automatically instantiated, filled, and provided, via DI.

To learn more about customizing DI in ASP.NET Core 6.0, let's have a look at the next chapter.

Further reading

You can refer to the following source for more information:

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Second edition updated and enhanced to cover the latest .NET 6 features and changes
  • Learn authentication and authorization techniques for securing your web apps from a .NET veteran
  • Discover best practices for configuring ASP.NET Core, from user interface design to hosting it on platforms

Description

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.

Who is this book for?

This book is for .NET developers who’ve already covered the basics and are now looking to learn more about changing default behaviors of the framework to help improve the performance of their applications. Intermediate-level knowledge of ASP.NET core and C# is a must before you get started; there’s no refresher and very little theory in this book.

What you will learn

  • Explore various application configurations and providers in ASP.NET Core 6
  • Enable and work with caches to improve the performance of your application
  • Understand dependency injection in .NET and learn how to add third-party DI containers
  • Discover the concept of middleware and write your middleware for ASP.NET Core apps
  • Create various API output formats in your API-driven projects
  • Get familiar with different hosting models for your ASP.NET Core app

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Dec 31, 2021
Length: 204 pages
Edition : 2nd
Language : English
ISBN-13 : 9781803243818
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Dec 31, 2021
Length: 204 pages
Edition : 2nd
Language : English
ISBN-13 : 9781803243818
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just Mex$85 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just Mex$85 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total Mex$ 3,322.97
Customizing ASP.NET Core 6.0
Mex$676.99
C# 10 and .NET 6 – Modern Cross-Platform Development
Mex$1640.99
An Atypical ASP.NET Core 6 Design Patterns Guide
Mex$1004.99
Total Mex$ 3,322.97 Stars icon
Banner background image

Table of Contents

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

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
(6 Ratings)
5 star 33.3%
4 star 33.3%
3 star 33.3%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Julian Ueber Jun 26, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is a great book for practicing and improving your knowledge in asp.net. I can recommend it to every .NET developer who wants to either learn new concepts or strengthen their existing programming skills.The author does a great job introducing the different topics and provides several examples and a repository to work with on github. It is definitely worth the money.
Amazon Verified review Amazon
Alvin Ashcraft Jan 31, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I recently received a review copy of Customizing ASP.NET Core 6.0 in eBook format. This is not your run-of-the-mill “getting started with ASP.NET Core” book. There are plenty of books and other online resources to get started building web applications with .NET. This book assumes you are familiar with the basics of ASP.NET Core development and dives right into the intermediate and advanced concepts (the good stuff). These are the things developers need to understand to build robust, scalable, performant web applications.I won’t re-hash the entire table of contents for you, but some of the most important (in my opinion) topics covered are:Writing a BackgroundServiceWriting Custom MiddlewareWorking with ASP.NET Core Identity and Customizing Identity ManagementCustom ModelBinders and ActionFiltersCaching conceptsThe sample code for each chapter is concise, self-contained, and can be applied to real-world applications. All this sample code is freely available to readers on GitHub. I love that Packt using GitHub for their books’ sample code. It’s a wonderful way for readers to work with the code and interact with the author and other community members. Readers have provided some great feedback to me through GitHub issues on my WinUI book‘s repository.The author does an excellent job covering the topics that are important to enterprise web application developers using the latest recommended techniques in ASP.NET Core 6. I would recommend this book to ASP.NET Core developers or other experienced .NET developers looking to get started building web apps.
Amazon Verified review Amazon
Justin Horner Mar 25, 2022
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
There are plenty of books available that will teach you how to get started with ASP.NET development. That’s not what this book is about. This book is about fine-tuning, giving you more control over your ASP.NET 6 applications.The author doesn’t waste a second. The first chapter brings value immediately by covering the cross-cutting concern of logging; configuration, creating custom loggers, and using third-party logging providers.Every chapter covers customizations for a different aspect of ASP.NET: App configuration, dependency injection, HTTPS and Kestrel, hosting models, ASP.NET Core Identity, writing custom middleware, and much more.If you work with ASP.NET, do yourself a favor and get this book as a reference because I believe there’s something here for everyone.
Amazon Verified review Amazon
Sarita Nag Jun 09, 2022
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
This book covers everything you need to know about ASP.NET core. Author has described the step-by-step implementation of ASP.NET core.I'll keep this book in mind when folks ask for recommendations about learning more about ASP.NET core.
Amazon Verified review Amazon
Sami Jan 18, 2022
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
If - after going through the below list - there are multiple topics that you want to learn more about, this book might be for you.It teaches you how to customize logging, e.g. by plugging in a third-party logging provider.It explains how to use typed configurations to load configuration sections into plain objects. It also describes how to use .ini files and get an increased understanding of configuration layers (e.g. environment variables overriding configuration files).Using a third-party dependency injection container.Working with certificates.Working with Nginx and Apache as reverse proxies.Working with / building background (non-HTTP) services.Walkthrough of the middleware workflow.Introduces health checks for when you want your application play nice with container orchestrators such as Kubernetes.Working with EF Core, including updating your database with migrations.Using the aspnet-codegenerator tool to scaffold authentication views.Integrating IdentityManager2 into your solution.Extending the formats that your controllers can consume and produce, including accepting and outputting blocks of CSV formatted data and dealing with the vCard format.Introduction to API testing with Postman.Dealing with cross-cutting concerns through Action Filters.Caching data - static files, controller outputs, service/provider outputs and caching of partial views.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.