Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using with HttpClientFactory #6

Open
Martin-Andersen opened this issue May 10, 2021 · 2 comments
Open

Using with HttpClientFactory #6

Martin-Andersen opened this issue May 10, 2021 · 2 comments

Comments

@Martin-Andersen
Copy link

Trying to get it to work using the IHttpClientFactory.
I am getting null in the HttpClientInterceptorEventArgs e argument.

 public static async Task Main(string[] args)
        {
            var b = WebAssemblyHostBuilder.CreateDefault(args);
            b.RootComponents.Add<App>("#app");
            b.Services.AddHttpClientInterceptor();

            // Setup the http client
            var samsonApiUrl = new Uri(b.HostEnvironment.BaseAddress + "api/");
            b.Services.AddHttpClient("Api", (serviceProvider,client) =>
            {
                client.BaseAddress = samsonApiUrl;
                client.EnableIntercept(serviceProvider);
            }).AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();
            // Supply HttpClient instances that include access tokens when making requests to the server project
            b.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>().CreateClient("Api"));
           
            var scope = b.Configuration.GetSection("Scope").Value;
            b.Services.AddMsalAuthentication(options =>
            {
                options.UserOptions.RoleClaim = "role";
                b.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication);
                options.ProviderOptions.DefaultAccessTokenScopes.Add(scope);
            }).AddAccountClaimsPrincipalFactory<CustomUserFactory>();
            
            b.Services.AddOptions();
            b.Services.AddAuthorizationCore();
            
            b.Services.AddScoped<HttpInterceptorService>();
            b.Services.AddTransient<ILoggingTestService, LoggingTestService>();

            await b.Build().RunAsync();
        }

  public class HttpInterceptorService
    {
        private readonly HttpClientInterceptor _interceptor;
        private readonly NavigationManager _navManager;

        public HttpInterceptorService(HttpClientInterceptor interceptor, NavigationManager navManager)
        {
            _interceptor = interceptor;
            _navManager = navManager;
        }

        public void MonitorEvent() => _interceptor.AfterSend += InterceptResponse;

        private void InterceptResponse(object sender, HttpClientInterceptorEventArgs e)
        {
            if (e.Response.IsSuccessStatusCode) return;
            
            var responseCode = e.Response.StatusCode;

            string message;
            switch (responseCode)
            {
                case HttpStatusCode.NotFound:
                    _navManager.NavigateTo("/404");
                    message = "The requested resorce was not found.";
                    break;
                case HttpStatusCode.Unauthorized:
                case HttpStatusCode.Forbidden:
                    _navManager.NavigateTo("/unauthorized");
                    message = "You are not authorized to access this resource. ";
                    break;
                default:
                    _navManager.NavigateTo("/500");
                    message = "Something went wrong, please contact Administrator";
                    break;
            }
            throw new HttpRequestException(message);
        }

        public void DisposeEvent() => _interceptor.AfterSend -= InterceptResponse;

    }
@jsakamoto
Copy link
Owner

Hi, @Martin-Andersen

Unfortunately, I'm not succeeded in reproducing the problem yet.

I tried to create the project, same as you disclosed partially, but that project I created was worked fine.

I'll attach my project to this comment.

App1.zip

However, as you can see, this project is not exactly the same as the code fragments that you explained.

So please attach the whole project as a zip package into this issue thread to let me able to build it, run it, reproduce the problem.

@ISCDiegoGuerrero
Copy link

ISCDiegoGuerrero commented Dec 27, 2022

I have a similar problem, i'm using IHttpClientFactory and Radzor Dialog in the BeforeSend to prevent multiples clicks but the request doesnt proceed after the Dialog is launched. I'm using a confirm dialog and i realized that the request proceed after close manually the dialog.

`
protected override void OnInitialized() {
base.OnInitialized();
Interceptor.BeforeSendAsync += Interceptor_BeforeSendAsync;
Interceptor.AfterSend += Interceptor_AfterSend;
}

	protected virtual async Task Interceptor_BeforeSendAsync(object sender, HttpClientInterceptorEventArgs e) {
		await DialogService.Alert("Espera un momento por favor", "Atención", new AlertOptions() {
			Top = "25px",
			ShowTitle = false,
			OkButtonText = "Aceptar"
		});
	}

	protected virtual void Interceptor_AfterSend(object sender, HttpClientInterceptorEventArgs e) {
		DialogService.Close();
	}

	public virtual void Dispose() {
		Interceptor.BeforeSendAsync -= Interceptor_BeforeSendAsync;
		Interceptor.AfterSend -= Interceptor_AfterSend;
	} 

`

Thanks.

Update:

Ready, i only change the BeforeSendAsync to BeforeSend

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants