I have an ASP.NET Core 8.0 MVC (upgraded from .NET 6.0) project; it's working fine in a Docker container except for the pages that contain Blazor code. I'm getting an error
blazor.server.js:1 [2025-04-01T04:53:37.291Z] Error: System.Net.Http.HttpRequestException: Connection refused (localhost:32784)
After investigation, I found that HttpRequest in .razor page was causing the issue.
protected async override void OnInitialized()
{
var request = new HttpRequestMessage(HttpMethod.Get, uri);
var response = await client.SendAsync(request);
}
Program.cs
:
builder.Services.AddServerSideBlazor().AddCircuitOptions(options => { options.DetailedErrors = true; });
builder.Services.AddControllersWithViews();
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.Services.AddDistributedMemoryCache();
builder.Services.AddHttpClient();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseMigrationsEndPoint();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseSession();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapRazorPages();
app.MapBlazorHub();
.csproj
:
<PackageReference Include="HtmlAgilityPack" Version="1.11.43" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Server" Version="8.0.14" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="8.0.14" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="8.0.14" />
<PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="8.0.14" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.14" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.14">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.21.0" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="8.0.7" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="System.Linq.Dynamic.Core" Version="1.2.19" />
We can find the issue is related to the httpclient
from the error message.
System.Net.Http.HttpRequestException: Connection refused (localhost:32784)
We can fix it by using configurations like below.
builder.Services.AddHttpClient("MyClient", client =>
{
// you can use host.docker.internal in docker environment
client.BaseAddress = new Uri("http://host.docker.internal:your_port/");
// or use below setting according to our needs
// client.BaseAddress = new Uri("http://api-service:8080/");
});