Home > Backend Development > C++ > How Have ASP.NET Core's Program and Startup Classes Evolved Across Different Versions?

How Have ASP.NET Core's Program and Startup Classes Evolved Across Different Versions?

Linda Hamilton
Release: 2025-01-13 16:09:43
Original
576 people have browsed it

How Have ASP.NET Core's Program and Startup Classes Evolved Across Different Versions?

ASP.NET Core’s Program and Startup class evolution

This article explores the evolution of the Program and Startup classes in different ASP.NET Core versions.

ASP.NET Core 6.x

ASP.NET Core 6.x has major changes to the Program and Startup classes:

  • No need for Program.Main() template code when using top-level statements.
  • Implicit using directive.
  • The Startup class is no longer needed, all code is in the Program file.
  • Introduces WebApplication and WebApplicationBuilder.

Example of Program.cs file for ASP.NET Core 6.x:

<code class="language-csharp">public class Program
{
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);

        // 配置服务
        builder.Services.AddControllersWithViews();

        var app = builder.Build();

        // 配置 HTTP 请求管道
        app.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");

        app.Run();
    }
}</code>
Copy after login

ASP.NET Core 3.x to 5.x

ASP.NET Core 3.x introduces a generic host builder to support worker services:

<code class="language-csharp">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>();
            });
}</code>
Copy after login
The

Startup class is similar to version 2.x.

ASP.NET Core 2.x

In ASP.NET Core 2.x, there is no need to instantiate Startup in the IConfiguration constructor because it is injected by the DI system:

<code class="language-csharp">public Startup(IConfiguration configuration, IHostingEnvironment env)
{
    this.HostingEnvironment = env;
    this.Configuration = configuration;
}</code>
Copy after login

ASP.NET Core 1.x

ASP.NET Core 1.x requires explicitly loading the Startup file in appsettings:

<code class="language-csharp">public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddEnvironmentVariables();

    this.Configuration = builder.Build();
}</code>
Copy after login

Gets valueappsettings.json from

There are two main ways to get a value from appsettings.json:

Simple method

Inject the entire configuration into a controller or class via IConfiguration and get the desired value using the specified key:

<code class="language-csharp">public class AccountController : Controller
{
    private readonly IConfiguration _config;

    public AccountController(IConfiguration config)
    {
        _config = config;
    }

    public IActionResult ResetPassword()
    {
        var vm = new ResetPasswordViewModel
        {
            PasswordRequiredLength = _config.GetValue<int>("AppIdentitySettings:Password:RequiredLength"),
            RequireUppercase = _config.GetValue<bool>("AppIdentitySettings:Password:RequireUppercase")
        };

        return View(vm);
    }
}</code>
Copy after login

Options Pattern

For multiple or complex settings, Options mode uses classes to represent a hierarchy of configurations:

  1. Define configuration classes to represent the structure of application settings. For example:
<code class="language-csharp">public class AppIdentitySettings
{
    public UserSettings User { get; set; }
    public PasswordSettings Password { get; set; }
    public LockoutSettings Lockout { get; set; }
}

// ... (UserSettings, PasswordSettings, LockoutSettings classes as before) ...</code>
Copy after login
  1. Register configuration instance in Startup of ConfigureServices:
<code class="language-csharp">var identitySettingsSection = _configuration.GetSection("AppIdentitySettings");
services.Configure<AppIdentitySettings>(identitySettingsSection);</code>
Copy after login
  1. Inject IOptions<AppIdentitySettings> into the controller/class that uses it:
<code class="language-csharp">public class AccountController : Controller
{
    private readonly AppIdentitySettings _appIdentitySettings;

    public AccountController(IOptions<AppIdentitySettings> appIdentitySettingsAccessor)
    {
        _appIdentitySettings = appIdentitySettingsAccessor.Value;
    }

    public IActionResult ResetPassword()
    {
        var vm = new ResetPasswordViewModel
        {
            PasswordRequiredLength = _appIdentitySettings.Password.RequiredLength,
            RequireUppercase = _appIdentitySettings.Password.RequireUppercase
        };

        return View(vm);
    }
}</code>
Copy after login

The above is the detailed content of How Have ASP.NET Core's Program and Startup Classes Evolved Across Different Versions?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template