Search code examples
c#httpsblazorasp.net-core-8

Base address of HttpClient not been assigned anymore on Blazor Web App


The code shown here works in an ASP.NET Core 8.0 Blazor server-side project, but it is not working in a Blazor Web App built with "Interactive render mode: Server" and "Interactivity location: Global" (The app will not start with the base address selected, which should be https://localhost:7122/Identity/Account/Login?ReturnUrl=%2F ). I read this article on Microsoft documents but I hope I don't have to go that route and that there is a simpler solution cause my projects are all server side only.

program.cs
    builder.Services
           .AddScoped(sp => new HttpClient 
                                { 
                                    BaseAddress = new Uri("https://localhost:7122/")

                            });

Solution

  • As the document said, for client-side rendering (CSR), which includes Interactive WebAssembly components and Auto components that have adopted CSR, calls are made with a preconfigured HttpClient registered in the Program file of the client project (BlazorApp.Client):

    builder.Services.AddScoped(sp =>
        new HttpClient
        {
            BaseAddress = new Uri(builder.Configuration["FrontendUrl"] ?? "https://localhost:5002")
        });
    

    So if you are using the server-side rendering (SSR currently you are using), which includes prerendered and interactive Server components, prerendered WebAssembly components, and Auto components that are prerendered or have adopted SSR, calls are made with an HttpClient registered in the Program file of the server project.

    Like below:

    builder.Services.AddHttpClient("localtest", httpClient =>
    {
        httpClient.BaseAddress = new Uri("https://localhost:7047");
    
    });
    

    Usage:

    @page "/"
    @inject IHttpClientFactory _httpClientFactory
    <PageTitle>Home</PageTitle>
    
    <h1>Hello, world!</h1>
    
    Welcome to your new app.
     
    @code{
    
        protected override async Task OnInitializedAsync()
        {
            var httpClient = _httpClientFactory.CreateClient("localtest");
            var httpResponseMessage = await httpClient.GetAsync(
                "WeatherForecast");
      
    
            if (httpResponseMessage.IsSuccessStatusCode)
            {
                using var contentStream =
                    await httpResponseMessage.Content.ReadAsStreamAsync();
    
                
            }
        }
    
    
    }
    

    Result:

    enter image description here