How can I call a controller method inside startup.cs of ASP.Net Core API? I want to build the cache on application start. Please help. Thanks in advance
2 Answers
You can not and you shall not. Requests require a connection and at the point in startup the application hasn't been fully configured/booted up yet. Also request require an instance of http context (which basically represents the request), which you can't do from Startup
.
Basically it boils down to two options:
Create an powershell/batch/bash script which will call the endpoint, when the application is deployed or started.
If you use IIS or Azure App Service to host your application, you can use Custom Warm-up settings in
web.config
.<applicationInitialization> <add initializationPage="/" hostName="[app hostname]" /> <add initializationPage="/Home/About" hostname="[app hostname]" /> </applicationInitialization>
Option is to refactor your code and pull the things that require caching into a service, then resolve it during application startup and run it once. With ASP.NET Core this should be done in
Program.cs
'sMain
method.See my answer here to see how you could set up warm-up during application startup. The post is about applying migrations, but same technique can be applied for cache warm-up.
Do not run warm-up within
Startup.Configure
as it was common in ASP.NET Core 1.x, because tools likedotnet ef ...
will execute it while discovering theDbContext
.

- 61,549
- 15
- 193
- 205
You can pull out logic of a method of the controller in separate service and use it in case of start applications