Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
458 views
in Technique[技术] by (71.8m points)

c# - JavaScript interop calls error when using IHttpCLientFactory in Blazor Server App

I have a blazor server app that consumes asp.net core web api. Below is the settings in the server app startup file

services.AddHttpClient(
                "webapi",
                client =>
                {
                    client.BaseAddress = new Uri(Configuration.GetSection("Configs").GetSection("APIUrl").Value);
                    client.DefaultRequestHeaders.Add("User-Agent", "BlazorServer");
                })

Below is the constructor

    private readonly IHttpClientFactory client;
    public AuthService(IHttpClientFactory client,ILocalStorageService localStorage,AuthenticationStateProvider authenticationStateProvider)
    {
        this.client = client;
        this.localStorage = localStorage;
        this.authenticationStateProvider = authenticationStateProvider;
    }

and the AuthService.Login method that calls the api using the IHttpCLientFactory

public async Task<Result> Login(LoginRequestModel model)
    {
        try
        {
            //string baseUrl = "https://localhost:44326/";
            //HttpClient http = new HttpClient();
            //var response = await http.PostAsJsonAsync($"{baseUrl}{LoginPath}", model);
            var _httpclient = client.CreateClient("webapi");
            var response = await _httpclient.PostAsJsonAsync(LoginPath, model);

            if (!response.IsSuccessStatusCode)
            {
                var errors = await response.Content.ReadFromJsonAsync<string[]>();

                return Result.Failure(errors);
            }

This give the error

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.

But when I comment out the IHpptClientFactory instance and uncomment the httpclient instance it's able to call the web api endpoint successfully

Login.Razor component

@page "/account/login"
<div class="mx-auto" style="max-width: 400px; margin-top:0px;">
    <EditForm Model="model" OnValidSubmit="SubmitAsync">

        <ErrorsList ShowErrors="ShowErrors" Errors="Errors" />


        <!-- Default form login -->
        <div class="modal-dialog cascading-modal" role="document">

            <!--Content-->
            <div class="modal-content">

                <!--Header-->
                <div class="modal-header primary-color white-text">
                    <h4 class="title">
                        <i class="fa fa-lock"></i> Login
                    </h4>
                </div>
                <!--Body-->
                <div class="modal-body">
                    <DataAnnotationsValidator />
                    <ValidationSummary />
                    <!-- Material input name -->
                    <div class="md-form form-sm">
                        <i class="fa fa-envelope prefix"></i>
                        <input type="text" id="eml" @bind-value="model.Email" class="form-control form-control-sm">
                        <label for="eml">Your email</label>
                    </div>

                    <!-- Material input email -->
                    <div class="md-form form-sm">
                        <i class="fa fa-lock prefix"></i>
                        <input type="password" id="pwd" @bind-value="model.Password" class="form-control form-control-sm">
                        <label for="pwd">Your password</label>
                    </div>

                    <div class="d-flex justify-content-around">
                        <div>
                            <!-- Remember me -->
                            <div class="custom-control custom-switch">
                                <input type="checkbox" class="custom-control-input" id="customSwitches">
                                <label class="custom-control-label" for="customSwitches">Remember me</label>
                            </div>
                        </div>
                        <div>
                            <!-- Forgot password -->
                            <a href="">Forgot password?</a>
                        </div>
                    </div>

                    <div class="text-center mt-4 mb-2">
                        <button class="btn btn-primary">
                            Login
                            <i class="fa fa-send ml-2"></i>
                        </button>
                    </div>
                    <div class="text-center">
                        <p>
                            Not a member?
                            <a href="">Register</a>
                        </p>

                        <!-- Social login -->
                        @*<p>or sign in with:</p>

                            <a href="#" class="mx-2" role="button"><i class="fab fa-facebook-f light-blue-text"></i></a>
                            <a href="#" class="mx-2" role="button"><i class="fab fa-twitter light-blue-text"></i></a>
                            <a href="#" class="mx-2" role="button"><i class="fab fa-linkedin-in light-blue-text"></i></a>
                            <a href="#" class="mx-2" role="button"><i class="fab fa-github light-blue-text"></i></a>*@
                    </div>
                </div>
            </div>
            <!--/.Content-->
        </div>
    </EditForm>

</div>

Login.Razor.cs component

public partial class Login
{
    private readonly LoginRequestModel model = new LoginRequestModel();

    public bool ShowErrors { get; set; }

    public IEnumerable<string> Errors { get; set; }

    private async Task SubmitAsync()
    {
        var result = await AuthService.Login(model);

        if (result.Succeeded)
        {
            ShowErrors = false;
            ToastService.ShowSuccess("You have successfully logged in");
            NavigationManager.NavigateTo("/");
        }
        else
        {
            this.Errors = result.Errors;
            this.ShowErrors = true;
        }
    }
}
question from:https://stackoverflow.com/questions/65894722/javascript-interop-calls-error-when-using-ihttpclientfactory-in-blazor-server-ap

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...