I want to update session variable in .net core. when i click on Start action method in controller and set session using
HttpContext.Session().SetInt32("Percentage",10)
and then I'm calling some synchrounous method which takes 5 minutes. After method completion, I want to set session again
HttpContext.Session().SetInt32("Percentage",35)
but this time I'm getting the error like:
{"IFeatureCollection has been disposed. Object name: 'Collection'."}
I'm getting the session from GetData() method which are calling in every 20 seconds from index.cshtml using ajax call.
HomeController:
private async Task<IActionResult> Start(string token, string btnClick)
{
HttpContext.Session.SetInt32("Percentage",10);
//Getting user details.. that takes 5 minutes;
GetUserDetails();
HttpContext.Session.SetInt32("Percentage", 35);
GetOtherData();
//Getting other data.. that also takes 5-10 minutes;
HttpContext.Session.SetInt32("Percentage", 55);
return View();
}
GetData Method:
This method calling from index.cshtml every 20 seconds and get the session data
public JsonResult GetData()
{
var res1 = HttpContext.Session.GetInt32("Percentage") + "," + _appData.status + "," + SyncCheckvar;
return Json(res);
}
Index.cshtml:
Here is the javascript code where I'm getting data from controller method GetData() in every 20 seconds.
<script>
var bar = $('#progress_bar');
var percentage = null;
function stopProgress() {
clearInterval(progress);
}
//var progress = setInterval(function () {
// percentage++;
// if (percentage <= 100) {
// $('#progress_percentage').html(percentage + '%');
// if (percentage > 10) {
// bar.css('width', percentage + '%');
// console.log(percentage);
// }
// }
var progress = $(document).ready(function () {
window.setInterval(function () {
$.ajax({
url: '@Url.Action("GetData", "Home")',
async: false,
type: "GET",
success: function (result) {
var res = result.split(',');
var res1 = res[0];
var res2 = res[1];
var res3 = res[2];
$("#progress_percentage").empty();
$("#progress_percentage").append(res1);
$("#text_container").empty();
$("#text_container").append(res2);
$("#syncstatus").empty();
$("#syncstatus").append(res3);
},
});
percentage = $('#progress_percentage').html();
//alert(percentage);
if (percentage < 100)
{
$('#progress_percentage').html(percentage + '%');
if (percentage > 10)
{
bar.css('width', percentage + '%');
// console.log(percentage);
if ($('#syncstatus').html() == "True")
{
if ($('#mainstart').is(':hidden'))
{
document.getElementById("syncbtndiv").style.display = "block";
//document.getElementById("mainstart").style.display = "block";
}
}
}
}
else
{
//stopProgress();
document.getElementById("loader_container").style.display = "none";
document.getElementById("triggerdetailsdiv").style.display = "none";
//document.getElementById("mainstart").style.display = "none";
if ($('#syncstatus').html() == "True")
{
if ($('#mainstart').is(':hidden'))
{
document.getElementById("syncbtndiv").style.display = "block";
}
}
}
},20000);
});
$(window).on('load', function () {
$.ajax({
url: '@Url.Action("GetData", "Home")',
async: false,
type: "GET",
success: function (result) {
var res = result.split(',');
var res1 = res[0];
var res2 = res[1];
$("#progress_percentage").empty();
$("#progress_percentage").append(res1);
$("#text_container").empty();
$("#text_container").append(res2);
},
});
percentage = $('#progress_percentage').html();
//alert(percentage);
if (percentage < 100) {
$('#progress_percentage').html(percentage + '%');
if (percentage > 10)
{
bar.css('width', percentage + '%');
// console.log(percentage);
}
}
else {
document.getElementById("loader_container").style.display = "none";
stopProgress()
}
});
</script>
Here is my 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)
{
string[] initialScopes = Configuration.GetValue<string>("DownstreamApi:Scopes")?.Split(' ');
services
// Use OpenId authentication
.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
// Specify this is a web app and needs auth code flow
.AddMicrosoftIdentityWebApp(Configuration)
// Add ability to call web API (Graph)
// and get access tokens
.EnableTokenAcquisitionToCallDownstreamApi(options =>
{
Configuration.Bind("AzureAd", options);
}, initialScopes)
// Use in-memory token cache
// See https://github.com/AzureAD/microsoft-identity-web/wiki/token-cache-serialization
.AddInMemoryTokenCaches()
.AddMicrosoftGraph(Configuration.GetSection("DownstreamApi"));
services.AddDistributedMemoryCache();
// Require authentication
services.AddControllersWithViews(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
})
.AddSessionStateTempDataProvider()
// Add the Microsoft Identity UI pages for signin/out
.AddMicrosoftIdentityUI();
//services.AddSingleton<AppData>();
services.AddScoped<AppData>();
services.AddScoped<HomeController>();
services.AddRazorPages()
.AddSessionStateTempDataProvider();
var path = Directory.GetCurrentDirectory();
services.AddDataProtection().PersistKeysToFileSystem(new DirectoryInfo($"{path}\\DataProtectionKeys\\Keys.xml"));
services.AddSession(options => {
options.IdleTimeout = TimeSpan.FromMinutes(30);//You can set Time
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
services.AddMvc(options=>options.EnableEndpointRouting=false);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
var path = Directory.GetCurrentDirectory();
loggerFactory.AddFile($"{path}\\SentimentLogs\\Sentiment_Log.txt");
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 scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseSession();
app.UseMvc(endpoints =>
{
endpoints.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
app.UseCookiePolicy();
}
}
I think i'm missing something. Please help me to implement session correctly in .net core 3.1