ASP.NET Core MVC设置中间件和路由
设置 MVC 和中间件
• 注册 MVC 服务到 IoC 容器
• 在 ASP.NET Core 管道里使用并配置 MVC 中间件
注册 MVC 服务仅需在 Startup 的 ConfigureServices 方法顶部加一句 services.AddMvc(); 即可。
public void ConfigureServices(IServiceCollection services)
{
//容器
services.AddMvc();
}
通过下面的代码在 Configure 方法里面使用MVC服务 和中间件:
如果要使用身份验证,要添加在配置路由之前
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILogger<Startup> logger)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app
app.UseStatusCodePages();
// 使用 wwwroot 下的静态文件
app.UseStaticFiles();
// 使用 MVC 并配置路由
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");//id?传递的参数表示可有可无;
});
}
下面继续中间件
- Map vs MapWhen
- Use 与 Run 的区别:
Use 里面可以接 next 继续执行后续中间件
Run 表示中间件执行的末端,不再执行后面的中间件
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Use(async (context, next) =>
{
//await context.Response.WriteAsync("Hello");
await next();
// 判断是否已经开始向响应的 body 输出内容
if (context.Response.HasStarted)
{
// 一旦已经开始输出,则不能再修改响应头的内容
}
await context.Response.WriteAsync("Hello2");
});
// 对特定路径指定中间件
app.Map("/abc", abcBuilder =>
{
abcBuilder.Use(async (context, next) =>
{
//await context.Response.WriteAsync("Hello");
await next();
await context.Response.WriteAsync("Hello2");
});
});
// 对特定条件指定中间件
app.MapWhen(context =>
{
return context.Request.Query.Keys.Contains("abc");
}, builder =>
{
// 与 Use 不同。
// Use 里面可以接 next 继续执行后续中间件
// Run 表示中间件执行的末端,不再执行后面的中间件
builder.Run(async context =>
{
await context.Response.WriteAsync("new abc");
});
});
app.UseMyMiddleware();
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
日志:
startup类中的Configure方法参数中加入 ILogger
调用logger.LohInformation("1234")即可
异常处理页面:(为安全性考虑,只有在开发者环境下才允许使用开发者异常页面)
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();//使用开发者异常页面,仅能面向开发者
}
Configure方法中的IHostingEnvironment env参数
env.IsDevelopment()-是否是开发环境
env.IsStaging()-是否为演示环境/模拟环境
或者使用:
env.IsEnvironment("IntegrationTest")其中的环境变量可以自己设置