statisch gerendert wird. Wenn die Vorbereitung aktiviert ist, können JavaScript Interop
Anrufe nur während des Onafterrenderasync -Lebenszyklus ausgeführt werden.
Code: Select all
builder.Services.AddScoped
();
builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddHttpClient("AuthenticatedClient", client =>
{
client.BaseAddress = new Uri(BaseUrl);
}).AddHttpMessageHandler();
< /code>
TokenService.cs
public class TokenService(ProtectedSessionStorage sessionStorage)
{
readonly string Key = "AccessToken";
public async Task SetAsync(string value)
{
try
{
await sessionStorage.SetAsync(Key, value);
}
catch { }
}
public async Task GetAsync()
{
try
{
string result = string.Empty;
var tokenResult = await sessionStorage.GetAsync(Key);
if (tokenResult.Success)
{
result = tokenResult.Value ?? string.Empty;
}
return result;
}
catch
{
return string.Empty;
}
}
}
< /code>
AuthTokenHandler.cs
public class AuthTokenHandler(TokenService tokenService) : DelegatingHandler
{
protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var token = await tokenService.GetAsync();//exception occurs in this line
if (!string.IsNullOrEmpty(token))
{
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
}
return await base.SendAsync(request, cancellationToken);
}
}
< /code>
Rasiermesserkomponente < /p>
string token = await tokenService.GetAsync(); //this line can retrieve token
var httpClient = HttpClientFactory.CreateClient("AuthenticatedClient");
var response = await httpClient.GetAsync(RelativeUrl);
if (response.IsSuccessStatusCode)
{
message = "Authorized";
var result = await response.Content.ReadAsStringAsync();
}
else if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
message = "Unauthorized";
}