在启动应用程序时调用api?

时间:2020-03-19 09:08:31

标签: rest asp.net-core controller

我目前处于需要在应用程序启动过程中调用控制器的情况? 控制器由应用程序本身托管。 有可能吗?只需在每次启动应用程序时触发它。

3 个答案:

答案 0 :(得分:1)

您可以在IHostApplicationLifetime方法上注入Startup.Configure(),然后为ApplicationStarted编写将在应用程序主机完全启动时触发的回调,并在回调方法中调用控制器动作。

Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
        services.AddHttpClient();
        //register other services   
}

private async Task<Action> OnApplicationStartedAsync(IHttpClientFactory httpClientFactory)
{
        var client = httpClientFactory.CreateClient();

        var request = new HttpRequestMessage(HttpMethod.Get, "https://localhost:44326/api/values");

        var response = await client.SendAsync(request);

        if (response.IsSuccessStatusCode)
        {
            //deal with the response
            var result = await response.Content.ReadAsStringAsync();
        }

        return null;
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime lifetime)
{

        IHttpClientFactory _clientFactory = app.ApplicationServices.GetService(typeof(IHttpClientFactory)) as IHttpClientFactory;

        lifetime.ApplicationStarted.Register(OnApplicationStartedAsync(_clientFactory).Wait);

       //other middlewares
} 

答案 1 :(得分:0)

在启动中,您可以致电:

public void ConfigureServices(IServiceCollection services)
{
    ...
    ...
    services.AddTransient<Interfaces.IService, Service.ServiceImplementator>();
    ...
    ...
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    ...
    ...
    Task.Run(() => {
                    app.ApplicationServices.GetRequiredService<Interfaces.IService>().DoWorkOnStartup();
                });
    ...
    ...
}

不要调用控制器操作,我认为您的控制器应该调用服务来完成工作。

答案 2 :(得分:0)

我结束了实现界面并在该界面内实现了所需的功能。

IControllerService.cs

public interface IControllerService
{
    void InsertIntoDB(string name);
}

Controller.cs

public InsertIntoDB(string name)
{
   ....
}

所以我可以在Startup.Configure中调用

startup.cs

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env, SchemaContext schemaContext, IControllerService controllerService)
{

    ....
    controllerService.InsertIntoDB("InitData")
}

我的API端点使用相同的接口进行调出