How to automatically call a function after pool recycling on IIS - c#

I would like to know-how in my web app written in C#.NET5 (+React) call function after IIS server use setting for recycling Web data on IIS -> Application Pool -> Recycling (Regular Time Interval (In Minutes)) set on 1440.
I load over 6 GB to memory (IMemoryCache) and it takes over 6 minutes then all data is loaded, I would like to call the load function to cache automatically after each cycle of the recycling period, before waiting for the user interaction.
I try it call in StartUp, in Main, and also with use IHostetServices, but in each case, I got an error then called service (my class with load method) is not recognized
3 Ways to Run Code Once at Application Startup in ASP.NET Core
I got these errors: when I try to call
{"Unable to resolve service for type Repository.DataFilters.Static.IGroupLoader' while attempting to activate 'Search.Startup'."}
When I try to call:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
// Add other security headers
app.UseMiddleware<SecurityHeadersMiddleware>();
app.UseSerilogRequestLogging();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
var isDev = env.EnvironmentName.Contains("Dev");
if (env.IsDevelopment() || isDev)
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
_GroupLoader.LoadGroupFiltersToMemory(); // try to call this method from my class
}
In ConfiguredService:
private readonly IGroupLoader _GroupLoader;
public Startup(IConfiguration configuration, IGroupLoader groupLoader)
{
Configuration = configuration;
_GroupLoader = groupLoader;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddMemoryCache();
// DB Contexts
services.AddDbContext<GroupContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
// Services
services.AddScoped<IGroupService, GroupService>();
// Repositories
services.AddScoped<IGroupLoader, GroupLoader>();
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/build";
});
}
This solution does not work:
<system.webServer>
<aspNetCore xdt:Transform="SetAttributes(startupTimeLimit)" startupTimeLimit="300">
</aspNetCore>
</system.webServer>
After IIS runs Recycling, Its looks like the App is not loaded, I must do an initial run like the open website link, is it possible to load the app automatically after the recycling process of IIS?
In Startup.cs I am not able to call await functions
Called function take over 8 minutes, then all data was loaded
Looks like then I must use: https://learn.microsoft.com/en-us/iis/get-started/whats-new-in-iis-8/iis-80-application-initialization#TOC301259895
Update 09.01.2022
After I set IIS and App to autostart I got this error:
I try to do this:
https://serverfault.com/questions/590865/how-can-i-warm-up-my-asp-net-mvc-webapp-after-an-app-pool-recycle
In web.config I set:
<applicationInitialization
remapManagedRequestsTo="Startup.html"
skipManagedModules="true" >
<add initializationPage="/subpage" />
</applicationInitialization>
Then when I try to call page /subpage (without using Startup.cs ->
Configure call of IMemoryCache function), the function to load into
IMemoryCache is not called, but when I run the app with Visual Studio or
deploy an app to IIS without autostart (warmup), a function is
called.
When I try to call function (with load IMemoryCache) via
Startup.cs -> Configure function, the function is called but IIS server start many (10-11 process) IIS Worker Process and I got
error upper, also Startup.html webpage is not called during the
loading process (I am not sure where must be located in .NET 5
Core Web App with React Solution).
I got this error:
System.InvalidOperationException: Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
This was maybe caused by many IIS Worker processes which calls the same function (in IMemoryCache loading function I have use lock())
Thank you

You can't inject your IGroupLoader dependency into your Startup.cs before the depedency injection has been setup - this is described by the error you provided.
According to this guide, you can inject a dependency in Configure once you've setup dependency injection in ConfigureServices.
i.e. you need to change:
from
private readonly IGroupLoader _GroupLoader;
public Startup(IConfiguration configuration, IGroupLoader groupLoader)
{
Configuration = configuration;
_GroupLoader = groupLoader;
}
to
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
from
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
to
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IGroupLoader groupLoader)
from
_GroupLoader.LoadGroupFiltersToMemory();
to
groupLoader.LoadGroupFiltersToMemory();

Related

Unable to create an object of type 'ApplicationDbContext'. Add an implementation of 'IDesignTimeDbContextFactory<ApplicationDbContext>' to the project

I am trying to create an Angular 8 project with asp.net Core 2.1.
Whenever I try to add migration using command
cmd command: dotnet ef migrations add init --project ../Lgn.DAL
The terminal throws error :
Unable to create an object of type 'ApplicationDbContext'. Add an implementation of 'IDesignTimeDbContextFactory' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time.
Startup.cs
``
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.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseCors(builder =>
{
builder.WithOrigins("http://localhost:4200");
builder.AllowAnyMethod();
builder.AllowAnyHeader();
});
app.UseHttpsRedirection();
app.UseMvc();
}
}``
Take a look at this solution to someone with a similar issue. Is your dependency injection setup all good? (number 2 on that list)
Here are the things to consider:
You get that error because to generate migrations you need either:
A DbContext with a default constructor (that is, a parameterless
constructor)
Being able to get the DbContext from ApplicationServices
(that is, Dependency Injection)
A design time factory that returns a
properly configured DbContext.

Overriding applicationUrl when running `dotnet Myapp.dll` with netcore 2.2

Let's say we take a default asp netcore 2.2 application generated from one of the default VS templates.
After running dotnet publish --Release we get a folder containing the app binaries.
Running dotnet MyDemo.dll stars the app on default http://localhost:5000.
How do I go about changing the default port and host?
I've tried setting ASPNETCORE_URLS environment variable with no effect.
Some additional context: I know for local development we can setup different profiles in launchSettings.json and we can use dotnet run command to select which profile to run. However, after publishing there's no launchSettings.json and running the binary directly using dotnet MyDemo.dll doesn't seem to allow any additional configuration.
Please see below the Startup class.
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.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/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.UseStaticFiles();
app.UseCookiePolicy();
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
app.UseMvc();
}
}
You should be having Program.cs where your Kestrel webserver is configured. In those configurations it should be possible to specify url for hostname and port. Check something like this:
var host = new WebHostBuilder()
.UseKestrel()
.UseUrls("http://localhost:60000", "http://localhost:60001")
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
You can find other methods to configure endpoints in docs
Btw, for ContinuosIntegration/ContinuosDelivery having endpoint settings in json would be better choise, so maybe you can look into improving your CI/CD pipeline.
Also there it should be possible to specify url in the command line using something like this

ASP.NET 5 Template crashes on first run

I'm starting a new project in VS 2015.
File -> New -> Project -> ASP.NET Web Application -> ASP.NET 5 Templates -> Web API
A project is initialized. I would assume that if I run the project with IIS Express a service would be available.
It runs through the startup methods.
public class Startup
{
public Startup(IHostingEnvironment env)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; set; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseIISPlatformHandler();
app.UseStaticFiles();
app.UseMvc();
}
// Entry point for the application.
public static void Main(string[] args) =>
WebApplication.Run<Startup>(args);
}
}
But then it crashes. I don't know how to implement global error handling.
I looked at this example.
But when I try to use System.Net.Http or System.Web.Http.ExceptionHandling they can't be found.
I also noticed that through intellisense it says Core 5.0 is no available.
Here is my project.json as requested.
{
"version":"1.0.0-*",
"compilationOptions":{
"emitEntryPoint":true
},
"dependencies":{
"Microsoft.AspNet.IISPlatformHandler":"1.0.0-rc1-final",
"Microsoft.AspNet.Mvc":"6.0.0-rc1-final",
"Microsoft.AspNet.Server.Kestrel":"1.0.0-rc1-final",
"Microsoft.AspNet.StaticFiles":"1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.FileProviderExtensions":"1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.Json":"1.0.0-rc1-final",
"Microsoft.Extensions.Logging":"1.0.0-rc1-final",
"Microsoft.Extensions.Logging.Console":"1.0.0-rc1-final",
"Microsoft.Extensions.Logging.Debug":"1.0.0-rc1-final"
},
"commands":{
"web":"Microsoft.AspNet.Server.Kestrel"
},
"frameworks":{
"dnx451":{
"frameworkAssemblies":{
"System.Web":"4.0.0.0"
}
},
"dnxcore50":{
}
},
"exclude":[
"wwwroot",
"node_modules"
],
"publishExclude":[
"**.user",
"**.vspscc"
]
}
Try to open Visual Studio Administrator Mode
I guess it depends on what is crashing - it's not clear from your description what crashes, when it crashes and how it crashes.
You can use UseExceptionHandler and UseDeveloperExceptionPage extension methods to configure an error handling page. This article describes it in more details.
If the exception happens during startup you may need to use UseCaptureStartupErrors extension method (it was recently renamed to CaptureStartupErrors).
Also, you already have logging enabled - the logs may also have some useful information. If you can't see logs because you log to the console consider logging to a file.
If this is IIS/IISExpress crashing check event log.
What is your runtime version ?
Maybe you can try scaffolding your application with the AspNet Yeoman generator and compare the files.
Personally I prefer to use the scaffolder as it is often up to date.
Hope this helps !

ASP.NET MVC 6 AspNet.Session Errors - Unable to resolve service for type?

Alright, so recently I've been having a lot of trouble using the new Microsoft.AspNet.Session middleware for ASP.NET vNext (MVC 6). The error I'm getting,
Unable to resolve service for type
'Microsoft.Framework.OptionsModel.ConfigureOptions[Microsoft.AspNet.Session.SessionOptions]
while attempting to activate
'Microsoft.AspNet.Session.SessionMiddleware'
occurs on all pages regardless of session use. The DNVM version I'm using is Beta5 x86 and all the packages in the project are Beta5 as well. The project itself is an attempt at porting an ASP.NET MVC 5 project to MVC 6 without much luck. Below are links to resources that may be important:
Project.json: http://tinyurl.com/project-json
Startup.cs: http://tinyurl.com/startup-cs
It seems to be a problem with my configuration but I'm not sure what to do about it... Pls send help Dx
Unable to resolve service for type 'Microsoft.AspNetCore.Session.ISessionStore' while attempting to activate 'Microsoft.AspNetCore.Session.SessionMiddleware'
If you get this error message in ASP.NET Core, you need to configure the session services in Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddSessionStateTempDataProvider();
services.AddSession();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseSession();
app.UseMvcWithDefaultRoute();
}
This code helps you...
In Startup.cs file
public void ConfigureServices(IServiceCollection services)
{
....
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(30);//We set Time here
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseSession();
app.UseMvc();
}
Thanks!!!
you can add session middleware into configure method in the startup.
public void ConfigureServices(IServiceCollection services) {
services.AddSession();
services.AddMvc();
}
Step 1: Install "Microsoft.AspNetCore.Session" this package.
Step 2: Add these functions in configure services function in the startup file.
(1). services.AddSession();
(2). services.AddDistributedMemoryCache();
Step 3: Add "app.UseSession()" use session function in Configure function in the startup file.
ASP.NET CORE 6.0
In program.cs file add this
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromSeconds(1800);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
Then
app.UseSession();
For more Read official doc
For ASP.NET 7 there is no longer a Startup.cs file, as it is merged with the Program.cs file. Instead add
builder.Services.AddSession();
builder.Services.AddDistributedMemoryCache();
above
var app = builder.Build();
Then you can add
app.UseSession();
I am using .net core 5 . I was getting the same issue
this is how i solved it
public void ConfigureServices(IServiceCollection services)
{
services.AddSession();
services.AddMvc();
}
I have added these and I have also added these ,
I added it to the startup.cs class
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
}
My problem is solved, I hope yours is solved too.
app.usesession() in the program.cs file; I deleted your method and it was fixed

Unable to use session in ASP.Net vNext Project

I have an ASP.Net vNext project that uses Session. But I am getting this error while trying to get/set values in the session.
An exception of type 'System.InvalidOperationException' occurred in Microsoft.AspNet.Http.Core.dll but was not handled in user code
Additional information: Session has not been configured for this application or request.
Here's my controller method:
[AllowAnonymous]
[HttpGet("/admin")]
public IActionResult Index()
{
if (Context.Session.GetString("UserName") == null) // error thrown here
{
return RedirectToAction("Login");
}
return View();
}
I have added the KVM package "Microsoft.AspNet.Session": "1.0.0-beta3" in my project.json file as well and have configured my application to use session via my Startup.cs like so:
public void ConfigureServices(IServiceCollection services)
{
// code removed for brevity
services.AddCachingServices();
services.AddSessionServices();
}
public void Configure(IApplicationBuilder app)
{
app.UseMvc();
app.UseInMemorySession(configure: s => s.IdleTimeout = TimeSpan.FromMinutes(30));
}
I have looked at the vNext documentation on Github but it does not provide much information about ASP.Net sessions. What am I doing wrong?
So I figured this out. The fix was quite simple actually. Since ASP.Net adds the middlewares sequentially into the request pipeline, all I needed to do was use the session middleware before using MVC. More info here: https://stackoverflow.com/a/29569746/832546
Fixed code:
public void Configure(IApplicationBuilder app)
{
app.UseInMemorySession(configure: s => s.IdleTimeout = TimeSpan.FromMinutes(30));
app.UseMvc();
}
Thanks to #acrhistof the link helped.
So if you are using RC1:
add this these dependencies in project.json:
"Microsoft.AspNet.Session": "1.0.0-rc1-final",
"Microsoft.Extensions.Caching.Memory": "1.0.0",
in Startup.cs file:
public void ConfigureServices(IServiceCollection services)
{
services.AddCaching();
services.AddSession();
services.AddMvc();
}
and
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseSession(); //outside of dev if (env.IsDevelopment())
....
}
It seems like things changed once again and the well-known ASP.NET session has to be configured differently in the rc1. (no UseInMemorySession() or other AppBuilder methods are related to Session, now it is added as a service).
In general Session has to be installed, configured, and then used. All these steps are quite new and somewhat unusual. Moreover, it depends on Cache:
Session is built on top of IDistributedCache, so you must configure
this as well, otherwise you will receive an error.
The quotation above is from ASP.NET 5 docs. All you need to do is described here: https://docs.asp.net/en/latest/fundamentals/app-state.html#installing-and-configuring-session.

Categories

Resources