Es ist in der Zeile httpClient.GetAsync abgestürzt. Zu Testzwecken wird dieser Aufruf ausgeführt, wenn die Seite mit der OnInitializedAsync-Funktion geladen wird.
Ich habe zwei verschiedene Tutorials befolgt, aber beide liefern das gleiche Ergebnis von .GetAsync Aufruf schlägt fehl: https://code-maze.com/blazor-webassembly-httpclient/ und
Bitte Hilfe.
Danke!
Serviceklasse:
Code: Select all
public class RecipeService : IRecipeService
{
private readonly HttpClient httpClient;
private string baseURL = clConstants.SERVER_PATH;
private string apiEndPoint = "getRecipeByID/";
public RecipeService(HttpClient httpClient)
{
this.httpClient = httpClient;
}
async Task IRecipeService.getRecipeByID(int id)
{
ConfigureHTTPClient();
string URL = clConstants.SERVER_PATH + apiEndPoint + id.ToString();
// Crashes on this line of code
var res = httpClient.GetAsync(URL).Result;
}
}
Code: Select all
public interface IRecipeService
{
//Task getRecipeByID(int id);
Task getRecipeByID(int id);
}
Code: Select all
protected override async Task OnInitializedAsync()
{
recipe = await RecipeService.getRecipeByID(currentCount);
}
Code: Select all
Program.cs
Code: Select all
builder.Services.AddScoped();
Schnittstelle
Code: Select all
public class RecipeService : IRecipeService
{
private readonly string apiEndPoint = "GetRecipeByID/";
private readonly IHttpClientFactory httpClientFactory;
private HttpClient CreateHttpClient() => httpClientFactory.CreateClient("MainApi");
private readonly JsonSerializerOptions jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
public RecipeService(IHttpClientFactory httpClientFactory)
{
this.httpClientFactory = httpClientFactory;
}
public async TaskgetRecipeByID(int id)
{
string URL = apiEndPoint + id.ToString();
var response = await CreateHttpClient().GetAsync(URL, HttpCompletionOption.ResponseHeadersRead);
var result = await response.Content.ReadAsStreamAsync();
var recipe = await JsonSerializer.DeserializeAsync(result, jsonOptions);
return recipe;
}
}
public interface IRecipeService
{
Task getRecipeByID(int id);
}
Code: Select all
builder.Services.AddHttpClient("MainApi", options =>
{
options.BaseAddress = new Uri(clConstants.SERVER_PATH);
});
builder.Services.AddSingleton();
Code: Select all
@inject IRecipeService RecipeService
private List recipe { get; set; }
public interface IRecipeService
{
Task getRecipeByID(int id);
}