amirsajjad yousefi
amirsajjad yousefi

Reputation: 5

How to automatically call method or IActionResult in ASP.NET Core api console or service start

I want to call a method when I start my console api or service starts.

I have tried this code in my launchsettings and it works when I start my api project with Visual Studio and my Get method is automatically called at start.

But the problem is when I publish my code as console app or publish as a Windows service, it's not working and I have to call the url http://localhost:8888 from a browser or Postman to call my method!

"Sadad.Api": {
    "commandName": "Project",
    "launchBrowser": true,
    "launchUrl": "Home",
    "applicationUrl": "http://localhost:8888",
    "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
    }
}

Upvotes: 0

Views: 1525

Answers (1)

Brando Zhang
Brando Zhang

Reputation: 28257

As far as I know, if you debug the asp.net core application from visual studio, the visual studio will help us to run the browser with the applicationUrl.

If you want to call one of your mvc or web api after the application has start up completely. I suggest you could inject IHostApplicationLifetime into Configure() method , then write the callback for ApplicationStarted that would be triggered when the application host has fully started.

More details, you could refer to below example:

Register httpclient service in Startup.cs ConfigureServices method

    public void ConfigureServices(IServiceCollection services)
    {

        services.AddHttpClient();

        services.AddControllersWithViews();


    }

Add lifetime.ApplicationStarted.Register callback in Configure method:

  public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime lifetime)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseStaticFiles();


        app.UseRouting();
        app.UseAuthorization();

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

        });

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

        lifetime.ApplicationStarted.Register(onApplicationStartedAsync(httpClientFactory).Wait);
    }



    private async Task<Action> onApplicationStartedAsync(IHttpClientFactory httpClientFactory)
    {

        var httpclient = httpClientFactory.CreateClient();

        var httpMessage = new HttpRequestMessage(HttpMethod.Get, "http://localhost:5000/api/values");

        var httpresponse = await httpclient.SendAsync(httpMessage);

        if (httpresponse.IsSuccessStatusCode)
        {
            string res = await httpresponse.Content.ReadAsStringAsync();
        }

        return null;
    }

Result:

enter image description here

Upvotes: 1

Related Questions