[Bug] Does not work inside Http DelegatingHandler in .NET MAUI Blazor
The following code works perfectly on Blazor WebAssembly but does not work in .NET MAUI Blazor:
[TransientService]
public class AuthorizationDelegatingHandler : DelegatingHandler
{
private readonly ILocalStorageService _localStorage;
public AuthorizationDelegatingHandler(ILocalStorageService localStorage)
{
_localStorage = localStorage;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
// This line perfectly works in Blazor WebAssebly app but does not work in .NET MAUI Blazor
LoggedInUserInfo loggedInUserInfo = await _localStorage.GetItemAsync<LoggedInUserInfo>(LocalStorageKey.LoggedInUserInfo);
if (loggedInUserInfo != null)
{
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", loggedInUserInfo.AccessToken);
}
HttpResponseMessage httpResponseMessage = await base.SendAsync(request, cancellationToken);
return httpResponseMessage;
}
}
The following line does work in any place of the .NET MAUI Blazor app but does not work inside AuthorizationDelegatingHandler:
LoggedInUserInfo loggedInUserInfo = await _localStorage.GetItemAsync<LoggedInUserInfo>(LocalStorageKey.LoggedInUserInfo);
And throws the following error:
System.NullReferenceException: Object reference not set to an instance of an object.
[DOTNET] at Microsoft.AspNetCore.Components.WebView.Services.WebViewJSRuntime.BeginInvokeJS(Int64 taskId, String identifier, String argsJson, JSCallResultType resultType, Int64
[DOTNET] targetInstanceId) in Microsoft.AspNetCore.Components.WebView.dll:token 0x6000113+0x0
[DOTNET] at Microsoft.JSInterop.JSRuntime.InvokeAsync[String](Int64 targetInstanceId, String identifier, CancellationToken cancellationToken, Object[] args) in Microsoft.JSInter
[DOTNET] op.dll:token 0x600003a+0x10a
[DOTNET] at Microsoft.JSInterop.JSRuntime.InvokeAsync[String](String identifier, CancellationToken cancellationToken, Object[] args) in Microsoft.JSInterop.dll:token 0x6000038+0x0
[DOTNET] at Microsoft.JSInterop.JSRuntimeExtensions.InvokeA
[DOTNET] sync[String](IJSRuntime jsRuntime, String identifier, CancellationToken cancellationToken, Object[] args) in Microsoft.JSInterop.dll:token 0x6000048+0xe
[DOTNET] at Microsoft.JSInterop.JSRuntimeExtens07-16 00:29:47.884 I/DOTNET (24839): at Blazored.LocalStorage.BrowserStorageProvider.GetItemAsync(String key, Nullable`1 cancellationToke
[DOTNET] n) in Blazored.LocalStorage.dll:token 0x6000005+0x24
[DOTNET] at Blazored.LocalStorage.LocalStorageService.<GetItemAsync>d__5`1[[MauiBlazor.Shared.Models.IdentityModels.LoggedInUserInfo, MauiBlazor.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].
[DOTNET] MoveNext() in Blazored.LocalStorage.dll:token 0x6000082+0x29
[DOTNET] at MauiBlazor.Shared.Extensions.LocalStorageServiceExtensions.GetUserInfoAsync(ILocalStorageService localStorage) in D:\GitHub\CleanArchitecture\src\ClientApps\MauiBlazor.Shared\Extensions\Loc
[DOTNET] alStorageServiceExtensions.cs:line 19
[DOTNET] at MauiBlazor.Shared.Common.AuthorizationDelegatingHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) in D:\GitHub\CleanArchitecture\src\ClientApps\MauiBlazor.Shared\Common\Authorizat
[DOTNET] ionDelegatingHandler.cs:line 30
[DOTNET] at System.Net.Http.Ht
[DOTNET] tpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken) in System.Net.Http
[DOTNET] at MauiBlazor.Shared.Services.UserService.LoginAsync(LoginModel loginModel) in D:\GitHub\CleanArchitecture\src\ClientApps\MauiBlazor.Shared\Services\UserService.cs:line 128
[DOTNET] at MauiBlazorApp.Components.IdentityComponents.Log
[DOTNET] inComponent.HandleValidSubmitAsync() in D:\GitHub\CleanArchitecture\src\ClientApps\MauiBlazorApp\MauiBlazorApp\Components\IdentityComponents\LoginComponent.razor.cs:line 51
Wow. I didn't think this packages would work at all with MAUI. I assume this is using the new WebView component?
As for the error, I have no idea at the moment. I've never created a MAUI app. I'll need to find some time to learn more about it. But I'll be honest, that could be a while. So if anyone else has any ideas who has used MAUI it would be appreciated.
@chrissainty Could you please take a look at https://github.com/Blazored/LocalStorage/issues/151. It seems these two issues are related as ILocalStorageService is also not working inside Http DelegatingHandler in the Blazor Server app.
Ah apologies. I didn't spot the service scoping. The issue here is that we register the service as scoped.
I'm going to add an additional method for registering services as transient which will solve this. No ETA right now though.
@chrissainty Please keep options for all the service lifetime, i.e Singleton, Scope, Transient although Singleton and Scope behave the same in Blazor WebAssembly. Most importantly, this should have been from the very beginning as you are not exposing the LocalStorageService class as public.
Thanks in advance for doing it as earlier as possible because it has been a blocking issue and no workaround.
I'm not sure about Singleton. This can cause some serious security issues in Blazor Server and I don't ever see a valid use case for Singleton. Right now transient and scoped will be the only options, unless someone can prove a valid use case.
@chrissainty Okay! Please go ahead and implement this.
I won't be implementing this at the moment as I don't have time. Feel free to contribute.
@chrissainty Sure! I am going to make a pull request.
@chrissainty I have tested thoroughly. This is in no way related to the BlazorLocalStorage lifetime. This is due to the way, JSInterop in Blazor has been designed.
Even if the BlazorLocalStorage lifetime is changed to Transient, it still throws the same error for .NET MAUI Blazor as it was throwing and for Blazor Server it throws the following error:
System.InvalidOperationException: JavaScript interop calls cannot be issued at this time. This is because the component is being statically rendered. When prerendering is enabled, JavaScript interop calls can only be performed during the OnAfterRenderAsync lifecycle method.
at Microsoft.AspNetCore.Components.Server.Circuits.RemoteJSRuntime.BeginInvokeJS(Int64 asyncHandle, String identifier, String argsJson, JSCallResultType resultType, Int64 targetInstanceId) in Microsoft.AspNetCore.Components.Server.dll:token 0x60002a4+0x25
at Microsoft.JSInterop.JSRuntime.InvokeAsync[TValue](Int64 targetInstanceId, String identifier, CancellationToken cancellationToken, Object[] args) in Microsoft.JSInterop.dll:token 0x600003a+0xda
at Microsoft.JSInterop.JSRuntime.InvokeAsync[TValue](String identifier, CancellationToken cancellationToken, Object[] args) in Microsoft.JSInterop.dll:token 0x6000038+0x0
at Microsoft.JSInterop.JSRuntimeExtensions.InvokeAsync[TValue](IJSRuntime jsRuntime, String identifier, CancellationToken cancellationToken, Object[] args) in Microsoft.JSInterop.dll:token 0x6000048+0xe
at Blazored.LocalStorage.BrowserStorageProvider.GetItemAsync(String key, Nullable`1 cancellationToken) in D:\GitHub\LocalStorage\src\Blazored.LocalStorage\BrowserStorageProvider.cs:line 23
at Blazored.LocalStorage.LocalStorageService.GetItemAsync[T](String key, Nullable`1 cancellationToken) in D:\GitHub\LocalStorage\src\Blazored.LocalStorage\LocalStorageService.cs:line 59
at MauiBlazor.Shared.Common.AuthorizationDelegatingHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) in D:\GitHub\LocalStorage\samples\MauiBlazor.Shared\Common\AuthorizationDelegatingHandler.cs:line 31
Hold on a minute. I know in MAUI essentially a small web server is spun up to render the Blazor components. But there isn't a full browser. Does Local storage even exist?! I'm guessing probably not hence the error you're seeing.
@chrissainty
But there isn't a full browser. Does Local storage even exist?
Yes! exists! I have checked inside Blazor components in .NET MAUI Blazor. It works perfectly fine.
Could you point to a resource which shows local storage exists? I can't seem to find anything. Also curious why use local storage when you're in a desktop environment?
@chrissainty Download this app and run it with Visual Studio 2019 latest preview.
Closing as there's been no further activity.