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

Ste*_*enL 3 iis asp.net-core

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

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

Tao*_*hou 5

一般情况下,应用程序启动成功后,就可以发送请求了。

对于 Application Start 事件,您可以IHostApplicationLifetime在 .net core 3.0 中尝试,如果您使用的是以前的版本,则可以尝试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?}");
        });
    }
}
Run Code Online (Sandbox Code Playgroud)