中间件
官方内置了很多种中间件:
使用中间件的常见形式:
app.UseWelcomePage(new WelcomePageOptions
{
Path = "/welcome"
});
中间件执行顺序:
app.Use(next =>
{
// 只允许一次
logger.LogInformation("app.Use()...");
// 每次请求都会运行的中间件代码
return async httpContext =>
{
logger.LogInformation("--- async httpContext");
if (httpContext.Request.Path.StartsWithSegments("/first"))
{
logger.LogInformation("--- First!!!!");
await httpContext.Response.WriteAsync("First!!!");
}
else
{
logger.LogInformation("--- next(httpContext)");
await next(httpContext);
}
};
});
UseDeveloperExceptionPage:开发者异常页面中间件,用于捕获在它之后的中间件中抛出的未处理异常。
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
Environment
内置的三种环境值:
- Development:开发环境
- Production:生产环境
- Staging:预览(演示)环境
环境值默认从 launchSettings.json 文件中获取:
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:63605",
"sslPort": 0
}
},
"profiles": {
// IIS 启动配置
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
// 命令行启动配置
"Tutorial.Web": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
文件伺服
通过 app.UseStaticFiles();
伺服静态文件后才能访问 index.html 等静态文件。
也可以使用 app.UserFileServer();
它将 Enable all static file middleware (except directory browsing) for the current request path in the current directory.