I am new in webassembly and after insert credentials the login page allways refresh and i cant test the httpclient response, how can i catch that?

Viewed 29

My code is this after lot of research :

  • program.cs
var apiUrl = new Uri(configuration["apiUrl"]);

//builder.Services.AddTransient<SkyPulsarAuthorizationMessageHandler>();

builder.Services.AddHttpClient("EdiRPX", httpClient =>
{
    httpClient.BaseAddress = apiUrl;  
})
    .AddTransientHttpErrorPolicy(builder => builder.WaitAndRetryAsync(new[]
    {
        TimeSpan.FromSeconds(1),
        TimeSpan.FromSeconds(5)
    }));
//.AddHttpMessageHandler<SkyPulsarAuthorizationMessageHandler>();

builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>()
    .CreateClient("EdiRPX"));
builder.Services.AuthClientSetup();
//*
builder.Services.AddBlazoredLocalStorage();
builder.Services.AddAuthorizationCore();
builder.Services.AddScoped<AuthenticationStateProvider, ApiAuthenticationStateProvider>();
//*
builder.Services.AddSingleton<SignalRClientService>();
builder.Services.AddTransient<IHelloService, HelloService>();
builder.Services.AddOidcAuthentication(options =>
{
    // Configure your authentication provider options here.
    // For more information, see https://aka.ms/blazor-standalone-auth
    builder.Configuration.Bind("Local", options.ProviderOptions);
    options.ProviderOptions.DefaultScopes.Add(builder.Configuration["apiUrl"]);
});

await builder.Build().RunAsync();

Handles Submit in Login.razor.cs

public partial class Login
    {
        private string? hello { get; set; }
        public IEnumerable<string> Errors { get; set; }
        private LoginModel model = new LoginModel();
        string backgroundUrl = "./resources/bg02.jpg";
        private LoginResult user;
        private bool loading;
        private bool ShowErrors;
        private bool ShowHello;
        [CascadingParameter]
        public Error? Error { get; set; }


        protected override void OnInitialized()
        {
            // redirect to home if already logged in            
            backgroundUrl = "./resources/bg02.jpg";
            StateHasChanged();
        }

        public Login()
        {
            user = new LoginResult();

        }

        private void ChangeBackground()
        {
            backgroundUrl = "./resources/2.jpg";
            StateHasChanged();
        }

        private async void HandleValidSubmit()
        {
            loading = true;
            ShowErrors = false;
            try
            {
                //hello = await helloService.Run();
                //ShowHello = true;
                //loading = false;
                user = await AuthService.Login(model);
                //var returnUrl = navigationManager.QueryString("returnUrl") ?? "";
                //navigationManager.NavigateTo(returnUrl);
                if (user.Success)
                {
                    navigationManager.NavigateTo("/");
                }
                else
                {
                    Errors = user.Errors;
                    ShowErrors = true;
                    //StateHasChanged();
                }
            }
            catch (Exception ex)
            {
                Error?.ProcessError(ex);
                //ShowErrors = true;
                //Errors = new[] { ex.Message };
                loading = false;
                //StateHasChanged();
            }
        }

    }
}

AuthService to handle with httpclient request

public async Task<LoginResult> Login(LoginModel loginModel)
        {            

            var content = JsonSerializer.Serialize(loginModel);
            var bodyContent = new StringContent(content, Encoding.UTF8, "application/json");
            var _httpClient = _httpFactory.CreateClient("EdiRPX");
            var loginResult = new LoginResult();
            try
            {
                **var authResult = await _httpClient.PostAsync("api/Login", bodyContent);**
                if (!authResult.IsSuccessStatusCode)
                {
                    ;
                    loginResult.Errors = new List<string>()
                    {
                        authResult.StatusCode.ToString()
                    };
                    loginResult.Success = false;
                    return loginResult;
                }
                var authContent = await authResult.Content.ReadAsStringAsync();
                loginResult = JsonSerializer.Deserialize<LoginResult>(authContent, _options);

                await _localStorage.SetItemAsync("authToken", loginResult.Token);
                ((ApiAuthenticationStateProvider)_authenticationStateProvider).MarkUserAsAuthenticated(loginModel.Email);
                _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", loginResult.Token);
                loginResult.Success = true;
                return loginResult;
            }
            catch (Exception ex)
            {
                if (loginResult != null)
                {
                    loginResult.Errors = new List<string>()
                    {
                        ex.Message
                    };
                    loginResult.Success = false;
                    return loginResult;
                }
                else
                {
                    return new LoginResult();
                }

            }
            //StateHasChanged();
        }

after this line of code

**var authResult = await _httpClient.PostAsync("api/Login", bodyContent);**

the login page alwways refreshs as is initializing and i dont get the chance to show error message, as the server is offline or other message like wrong credentials.

what i am doing wrong? thanks in advance

0 Answers
Related