如何判断自托管的ASP.NET Core应用程序何时准备接收请求?

时间:2019-10-08 21:46:05

标签: asp.net-core iis

我需要启动使用ASP.NET Core Web API进行通信的工作进程。我需要知道何时可以开始向该进程发送请求。到目前为止,我唯一看到的选择是让工作程序在完成父进程API的配置或通过“您还活着”请求轮询工作程序时进行调用。

是否有内置的机制?有更好的图案或设计吗?

1 个答案:

答案 0 :(得分:0)

通常,在成功启动应用程序之后,您将能够发送请求。

对于应用程序启动事件,您可以在.net core 3.0中尝试IHostApplicationLifetime,如果使用的是以前的版本,则可以尝试IApplicationLifetime,在以后的版本中将不再使用。

这是一个演示,用于在启动应用程序时注册事件。

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews().AddNewtonsoftJson();         
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime hostApplicationLifetime)
    {
        hostApplicationLifetime.ApplicationStarted.Register(() => {
            Console.WriteLine("Application is Started");
        });

        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();
        }
        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();        

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}