Search code examples
asp.net-coresessionhttpcontextblazor-server-side

HttpContext.Session in Blazor Server Application


I am trying to use HttpContext.Session in my ASP.NET Core Blazor Server application (as described in this MS Doc, I mean: all correctly set up in startup)

Here is the code part when I try to set a value:

var session = _contextAccessor.HttpContext?.Session;
if (session != null && session.IsAvailable)
{
    session.Set(key, data);
    await session.CommitAsync();
}

When this code called in Razor component's OnAfterRenderAsync the session.Set throws following exception:

The session cannot be established after the response has started.

I (probably) understand the message, but this renders the Session infrastructure pretty unusable: the application needs to access its state in every phase of the execution...

Question

Should I forget completely the DistributedSession infrastructure, and go for Cookies, or Browser SessionStorage? ...or is there a workaround here still utilizing HttpContext.Session? I would not want to just drop the distributed session infra for a way lower level implementation...

(just for the record: Browser's Session Storage is NOT across tabs, which is a pain)


Solution

  • Blazor is fundamentally incompatible with the concept of traditional server-side sessions, especially in the client-side or WebAssembly hosting model where there is no server-side to begin with. Even in the "server-side" hosting model, though, communication with the server is over websockets. There's only one initial request. Server-side sessions require a cookie which must be sent to the client when the session is established, which means the only point you could do that is on the first load. Afterwards, there's no further requests, and thus no opportunity to establish a session.

    The docs give guidance on how to maintain state in a Blazor app. For the closest thing to traditional server-side sessions, you're looking at using the browser's sessionStorage.