Blazor web app net 8 rendermode auto with API

Ángel Rubén Valdeolmos Carmona 586 Reputation points
2024-04-24T15:40:36.8+00:00

I am creating a web application with blazor web app and net 8 with rendermode Auto.

I have an api created in .net hosted on another server different from where the blazor web application will go.

The api needs a token in each call, I am having problems putting the token in each http request, I am using HttpClient with a Handler to retrieve that token in each request, for example, from the localStorage or sessionStorage.

The problem is that the server gives an error that localStorage or sessionStorage cannot be accessed, due to JavaScript interoperability. The component in WASM mode works correctly.

I tried:

<Routes @rendermode="new InteractiveServerRenderMode(prerender: false)" />

<HeadOutlet @rendermode="new InteractiveServerRenderMode(prerender: false)" />

But from the Handler on each request I can't access localStorage or sessionStorage.

What is the correct way to implement the Handler so that it works with components in Auto mode?

Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,396 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 56,846 Reputation points
    2024-04-24T19:45:26.4466667+00:00

    when the component is in prerender mode, there is no connection to the browser, so no javascript interop is allowed. prerender will only have access to site cookies, which you could use instead of local storage for prerender.

    to implement pre-render, on the host page request, the server creates an instance of the BlazorApp, and builds and renders the tree. the tree is converted to html, and the app is shut down. the html is rendered into the app div (along with persistent state json). The browser loads the page, renders the html, and loads the blazor bootstrap js. this js loads the wasm, or opens the signal/r connection and starts a new blazer server instance.

    to access local storage (or any jsinterop) you use the OnAfterRender{Async} override. this will only fire with blazer app instances tried to a browser.

    note: you can use the cascading parameter HttpContext to detect prerender:

    [CascadingParameter] HttpContext HttpContext {get; set; }
    bool IsPreRender => HttpContext != null;