Friday, May 5, 2023

How to enable Session in ASP.NET Core?

The middleware for the session is provided by the package Microsoft.AspNetCore.Session.

1. To use the session in ASP.NET Core application, we need to add this package to csproj file and add the Session middleware to ASP.NET Core request pipeline.

public void Configure(IApplicationBuilder app, TwebHostEnvironment env)

{

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

app.UseŠ½sts();

}

app.UseSession();

app.UseHttpsRedirection(); app.UseStaticFiles();

app.UseAuthentication();

app.UseRouting();

app.UseAuthorization();

app.useEndpoints (endpoints =>

{

endpoints.MapController Route(

name: "default",

pattern: "(controller-Home)/(action-Index}/{id}");

});

}