79311033

Date: 2024-12-27 06:10:49
Score: 0.5
Natty:
Report link

Hope all of this helps!

RecipeService & IRecipeService

public interface IRecipeService
{
    Task<ClRecipe> GetRecipeByID(int id);
}

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 Task<ClRecipe?> GetRecipeByID(int id)
    {
        //ConfigureHTTPClient();

        //string URL = clConstants.SERVER_PATH + apiEndPoint + id.ToString();
        
        string URL = $"{apiEndPoint}?id={id}";

        var response = await CreateHttpClient().GetAsync(URL, HttpCompletionOption.ResponseHeadersRead);
        var result = await response.Content.ReadAsStreamAsync();
        
        var recipe = await JsonSerializer.DeserializeAsync<ClRecipe>(result, jsonOptions);
        return recipe;

    }
}

Recipe.razor

@page "/recipe"
@inject IRecipeService recipeService

<h3>Recipe</h3>
@if (recipe is null)
{
    <p>Loading...</p>
}
else
{
    <p>@recipe.RecipeID</p>
    <p>@recipe.RecipeName</p>
}

@code {
    private ClRecipe? recipe { get; set; }

    protected override async Task OnInitializedAsync()
    {
        // recipe = await recipeService.GetRecipeByID(15); // not found
        
        recipe = await recipeService.GetRecipeByID(5);
        if (recipe is null)
        {
            recipe = new ClRecipe
            {
                RecipeID = -420,
                RecipeName = "Not Found"
            };
        }
    }
}

Program.cs

builder.Services.AddHttpClient("MainApi", options =>
{
    //options.BaseAddress = new Uri(clConstants.SERVER_PATH);
    options.BaseAddress = new Uri("https://localhost:7206/");
});

builder.Services.AddSingleton<IRecipeService, RecipeService>();

Supporting Links / Reads

IHttpClientFactory Info

Making Requests with HttpClient

Dependency Injection

await versus .Result related Stack question

HttpClient vs IHttpClientFactory

Reasons:
  • Probably link only (1):
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: wiseotter