ASP.NET 启动
最后修改于 2025 年 4 月 3 日
在本文中,我们将探讨 ASP.NET 8 中的 Startup 类。此类对于配置服务和应用程序的请求管道至关重要。
ASP.NET 是一个跨平台的、高性能的框架,用于构建现代 Web 应用程序。Startup 类集中了 ASP.NET 应用程序的配置。
基本定义
ASP.NET 中的 Startup 类负责配置服务和应用程序的请求处理管道。它包含两个主要方法。
ConfigureServices
用于将服务添加到依赖注入容器。Configure
定义了应用程序如何响应 HTTP 请求。
在 .NET 6 及更高版本中,Startup 模式是可选的,但仍然受支持。许多应用程序现在使用最小托管模型,所有配置都在 Program.cs 中完成。
ASP.NET Startup 示例
以下示例演示了一个基本的 ASP.NET 应用程序,该应用程序在 .NET 8 中使用了 Startup 类模式。
var builder = WebApplication.CreateBuilder(args); // Configure the host to use Startup class builder.Host.ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); var app = builder.Build(); app.Run();
这会设置应用程序主机以使用单独的 Startup 类进行配置。UseStartup
方法指定了 Startup 类。
public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime public void ConfigureServices(IServiceCollection services) { // Add services to the container services.AddControllers(); services.AddSwaggerGen(); // Add custom services services.AddSingleton<IWeatherService, WeatherService>(); // Configure options services.Configure<AppSettings>(Configuration.GetSection("AppSettings")); } // This method gets called by the runtime public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapGet("/", async context => { await context.Response.WriteAsync("Hello World!"); }); }); } }
Startup 类演示了 ConfigureServices
中的服务配置和 Configure
中的中间件管道设置。它使用依赖注入进行配置。
ConfigureServices
添加了 MVC 控制器、Swagger 文档、自定义天气服务,并从配置系统配置应用程序设置。
Configure
使用开发异常页面、HTTPS 重定向、路由、授权和终结点配置来设置请求管道。环境检查启用了特定于开发的特性。
此示例展示了服务注册和请求管道配置之间的关注点分离。Startup 类仍然是组织 ASP.NET 应用程序设置的强大模式。
来源
在本文中,我们探讨了 ASP.NET 8 中的 Startup 类。这种强大的模式有助于组织应用程序配置和中间件设置。