I have a Blazor webasemmbly app, it's using asp.net core as backend and Blazor wasm as frontend. I have a class that can check the HTTP issues like notfound, BadReqest, and ...
public class HttpInterceptorService
{
private readonly HttpClientInterceptor _interceptor;
private readonly NavigationManager _navManager;
private readonly RefreshTokenService _refreshTokenService;
public HttpInterceptorService(HttpClientInterceptor interceptor,
NavigationManager navManager,
RefreshTokenService refreshTokenService)
{
_interceptor = interceptor;
_navManager = navManager;
_refreshTokenService = refreshTokenService;
}
public void RegisterEvent() => _interceptor.AfterSend += HandleResponse;
public void RegisterBeforeSendEvent() =>
_interceptor.BeforeSendAsync += InterceptBeforeSendAsync;
public void DisposeEvent()
{
_interceptor.AfterSend -= HandleResponse;
_interceptor.BeforeSendAsync -= InterceptBeforeSendAsync;
}
private async Task InterceptBeforeSendAsync(object sender,
HttpClientInterceptorEventArgs e)
{
var absolutePath = e.Request.RequestUri.AbsolutePath;
if (!absolutePath.Contains("token") && !absolutePath.Contains("account"))
{
var token = await _refreshTokenService.TryRefreshToken();
if (!string.IsNullOrEmpty(token))
{
e.Request.Headers.Authorization =
new AuthenticationHeaderValue("bearer", token);
}
}
}
private void HandleResponse(object sender, HttpClientInterceptorEventArgs e)
{
if (e.Response == null)
{
_navManager.NavigateTo("/PageError");
throw new HttpResponseException("Server not available.");
}
var message = "";
if (!e.Response.IsSuccessStatusCode)
{
switch (e.Response.StatusCode)
{
case HttpStatusCode.NotFound:
_navManager.NavigateTo("/Page404");
break;
case HttpStatusCode.BadRequest:
break;
case HttpStatusCode.Unauthorized:
_navManager.NavigateTo("/unauthorized");
break;
default:
_navManager.NavigateTo("/PageError");
break;
}
throw new HttpResponseException(message);
}
}
}
this HTTP Interceptor does a great job, but the issue is when the client app (wasm) loses the connection to the server (for any reason like no internet, or server stop running and ...), it doesn't work and is not going to be useful. when the server doesn't run as well .
so searched I found that we have to check the signalR connection status but I couldn't find an example or tutorial on how to implement that.
I want to add it globally to the app.