ASP.NET 配置
最后修改于 2025 年 4 月 3 日
在本文中,我们将探讨 ASP.NET 8 中的 Configure 方法。此方法对于设置 ASP.NET 应用程序中的 HTTP 请求管道至关重要。
Configure 方法定义了应用程序如何响应 HTTP 请求。它允许添加中间件组件来处理请求和响应。
基本定义
ASP.NET 中的 Configure 方法是应用程序启动过程的一部分。它在 ConfigureServices 之后由运行时调用,用于设置请求管道。
此方法接受一个 IApplicationBuilder 参数和其他可选参数,如 IWebHostEnvironment。您可以在此处按顺序添加中间件组件。
中间件组件在 ASP.NET 中处理请求和响应。它们可以执行诸如身份验证、路由和静态文件提供之类的操作。
ASP.NET 配置示例
以下示例演示了 ASP.NET 8 中基本的 Configure 方法设置。
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
此示例展示了 ASP.NET 8 中的典型 Configure 设置。管道以生产环境的异常处理和 HTTPS 重定向开始。
UseStaticFiles 启用了 CSS 和 JavaScript 等静态文件的提供。UseRouting 和 UseAuthorization 设置了路由和身份验证中间件。
MapControllerRoute 方法定义了 MVC 控制器的默认路由模式。中间件注册的顺序至关重要,因为它决定了处理顺序。
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.Use(async (context, next) =>
{
// Logic before the next middleware
Console.WriteLine($"Request started: {context.Request.Path}");
await next.Invoke();
// Logic after the next middleware
Console.WriteLine($"Request completed: {context.Response.StatusCode}");
});
app.Use(async (context, next) =>
{
if (context.Request.Path.StartsWithSegments("/admin"))
{
context.Response.StatusCode = 403;
await context.Response.WriteAsync("Forbidden");
return;
}
await next();
});
app.MapGet("/", () => "Hello World!");
app.Run();
此示例演示了 Configure 管道中的自定义中间件。第一个中间件记录请求的开始和完成时间。
第二个中间件检查管理员路径,如果匹配则返回 403 Forbidden 响应。自定义中间件提供了对请求处理的精细控制。
MapGet 方法添加了一个简单的终结点,用于响应根路径上的 GET 请求。这展示了如何混合使用中间件和终结点路由。
来源
在本文中,我们探讨了 ASP.NET 8 中的 Configure 方法。这个强大的功能允许构建灵活的请求处理管道。