Reputation: 33
I have a Blazor Server Web App and an ASP.NET Core Web API running on localhost. I am trying to make HTTP requests from the Web App to the API but I cannot see any requests being made in the browser's Network tab or any responses from the API. Despite configuring CORS and setting the correct HttpClient.BaseAddress, the requests don’t seem to reach the API.
builder.Services.AddCors(options =>
{
options.AddDefaultPolicy(policy =>
{
policy.WithOrigins("http://localhost:5235")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
app.UseCors();
builder.Services.AddScoped(sp => new HttpClient
{
BaseAddress = new Uri("http://localhost:5213/")
});
@page "/test-api-connectivity"
@inject HttpClient HttpClient
<h3>Test API Connectivity</h3>
<button @onclick="FetchData">Test Connection</button>
<p>@responseMessage</p>
@code {
private string responseMessage = string.Empty;
private async Task FetchData()
{
try
{
var response = await HttpClient.GetAsync("api/locations");
responseMessage = response.IsSuccessStatusCode
? "Connection successful!"
: $"Connection failed: {response.StatusCode}";
}
catch (Exception ex)
{
responseMessage = $"Error: {ex.Message}";
}
}
}
/api/locations
returns 17,820 rows in Postman, so the API is functional.When clicking the button on the test page (TestApiConnectivity
or Locations
), I expect the browser to send a GET request to http://localhost:5213/api/locations
and return a response.
It has been frustrating to troubleshoot since: no HTTP requests are visible in the browser's Network and Console tab. The API does not log any received requests. And lastly, the Blazor page does not update with the response.
What could prevent my Blazor Server Web App from sending HTTP requests to the API, even though:
Upvotes: 0
Views: 167
Reputation: 553
This is normal and expected behavior. Your code is perfect, but in a Blazor Server application, your C# code (including HttpClient) runs on the server, not in the browser. When you call your API from Blazor Server, those requests never show up in the browser’s Network tab because they don’t originate from the client side, they originate from the server process. The browser’s Network tab only logs requests made directly by the browser (e.g., via JavaScript fetch/XHR).
You can confirm this by logging your API endpoint using Console.WriteLine()
, and you'll notice that it is being hit.
if you need it to run on the client side, you should invoke JavaScript code from your Blazor app. Take a look at the IJSRuntime
interface.
Upvotes: 0