我们以前在用asp.net mvc或者webform的时候,经常用用到Application里的事件 start,end等。我们在.net core 里也同样有类似的方法。
在Startup类里,Configure方法里添加一个参数IHostApplicationLifetime applicationLeftTime就可以了。具体写法如下:
IHostApplicationLifetime 为.netcore 3.1的写法,如果为.netcore 2.*,则用IApplicationLifetime
public void Configure(IApplicationBuilder app, IHostingEnvironment env,IHostApplicationLifetime applicationLeftTime)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
} applicationLeftTime.ApplicationStarted.Register(() =>
{
//里面可以写其他逻辑 Console.Write("ApplicationStarted");
}); applicationLeftTime.ApplicationStopped.Register(()=> {
//里面可以写其他逻辑
Console.Write("ApplicationStopped");
}); applicationLeftTime.ApplicationStopping.Register(() => {
//里面可以写其他逻辑
Console.Write("ApplicationStopping");
}); app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy(); app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}