我們以前在用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?}");
});
}