I have a server size Blazor app that needs to write something into a session when page is first loaded, and then read it from a session in that page and other pages.
Right now, that Session.String() is called in OnInitializedAsync() . However, I'm getting an exception "The session cannot be established after the response has started". From scant documentation that I found, this usually happens when SignalR is used with the app.
1) I don't think I'm using SignalR, unless it's configured by default to be used in server-side .net core code (In which case, how do I find out?) 2) I also tried putting the call in OnInitialized() and onAfterRender() (synchronous methods), which didn't help. 3) I think my HTTPContextAccessor and ISession are configured correctly, because I'm able to use Session.GetString() anytime, including right before the call to Session.SetString(). 4) I cannot switch to a client-size Blazor app for a variety of reasons. 5) I'm using app.UseEndpoints(), so app.useMvc() is commented out because they cannot be used at the same time.
Does anyone have any idea off the top of their head what could be wrong before I paste very large chunks of code here? The snippets of what I have so far are below
//Startup.cs
public IHttpContextAccessor HtppContextAccessor { get; }
// ...
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddHttpContextAccessor();
//services.AddMvc(); //TODO: DO I NEED IT?
services.AddDistributedMemoryCache(); //TODO : DO I NEED IT? // Adds a default in-memory implementation of IDistributedCache
services.AddSession();
//services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseSession();
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.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
//**************************************************************************
//myfile.razor
protected override async Task OnInitializedAsync()
{
var sampleValue = Session.GetString("testName1"); //this call is ok
Session.SetString("testName1", "testValue2"); //this is where exception occurs
}
Thank you