Search code examples
blazor-client-side

What is the entry point for adding code to Blazor?


I need to add some code to a Blazor WASM app that run as the application is starting up. I want to make a call to an API to get some settings to use during the rest of the application's lifetime.

I have verified that the API is configured correctly and that it returns data.

I've tried adding both MainLayout.razor.cs as well as App.razor.cs in order to make the call.
Neither of these worked. However when I add the SAME code to one of my other components (below), it works fine.

public class ViewMenuModel : ComponentBase
{
    [Inject] HttpClient Http { get; set; }
    [Inject] AppState AppState { get; set; }

    protected override async Task OnInitializedAsync()
    {
        Settings = await Http.GetJsonAsync<List<Settings>>("settings");
        UpdateSettings(Settings);
    }

    protected void UpdateSettings(List<Settings> settings)
    {
        AppState.SetSettings(settings);
    }
}

Is it possible that I'm just missing something? Is this kind of thing supposed to work from either MainLayout or App?? If so, what's the trick?


Solution

  • It's been some time since I asked this question initially, but I think it might be valuable for future people....

    When I started, I think we were on .Net core 3.1, since then, migrating to .net 6, there's actual Microsoft documentation on how to add these types of configurations

    https://learn.microsoft.com/en-us/aspnet/core/blazor/fundamentals/configuration?view=aspnetcore-6.0

    In Program.cs

    var http = new HttpClient()
    {
        BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)
    };
    
    builder.Services.AddScoped(sp => http);
    
    using var response = await http.GetAsync("cars.json");
    using var stream = await response.Content.ReadAsStreamAsync();
    
    builder.Configuration.AddJsonStream(stream);