In my Blazor WebAssembly project i connected a external openapi api by adding a ServiceReference in VisualStudio. After that the client side code is generated automatically.
In my Programm.cs i did:
builder.Services.AddScoped<CustomApi>(sp => new CustomApi(builder.Configuration["BaseUrl"], new HttpClient() { }));
this works fine if there is no authentication. For the authentication i wrote a custom AuthenticationStateProvider and store the jwt token in the localStorage.
How do i add the token to the Authentication-Header of the HttpClient?
There is nothing in the automatically generated code to manipulate the HttpClient before a request. Looks like that needs to be done here in the Programm.cs, but how can i access the local storage from Program.cs? It needs to be in a way that the token is added for every request, so that it doesn’t use a expired token, but that is something Scoped should to.
Of course it would be easy to just inject a httpclient and do it all manually, but there should be a way to do it with the automatically generated code.
seho is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.