Ich habe versucht:
1 . Cors-Konfiguration in WebAPI:
Code: Select all
builder.Services.AddCors(options =>
{
options.AddDefaultPolicy(policy =>
{
policy.WithOrigins("http://localhost:5235")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
app.UseCors();
Code: Select all
builder.Services.AddScoped(sp => new HttpClient
{
BaseAddress = new Uri("http://localhost:5213/")
});
Code: Select all
@page "/test-api-connectivity"
@inject HttpClient HttpClient
Test API Connectivity
Test Connection
@responseMessage
@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}";
}
}
}
- Die API funktioniert gut mit Postman und Swagger.
- Der Endpunkt /api/locations gibt in Postman 17.820 Zeilen zurück, sodass die API funktionsfähig ist.
- Ich sehe keine ausgehenden Anfragen auf der Registerkarte „Netzwerk“ des Browsers, wenn ich auf die Schaltfläche „Verbindung testen“ klicke.
- In der Browserkonsole werden keine Fehler angezeigt.
Code: Select all
TestApiConnectivity
Frage:
Was könnte meine Blazor Server-Webanwendung daran hindern, HTTP-Anfragen an zu senden? die API, obwohl:
- CORS konfiguriert ist,
- API mit Postman und Swagger funktioniert,
- Die HttpClient.BaseAddress ist festgelegt richtig?