Mike T.
Mike T.

Reputation: 61

How to read JSON file in a class library from Blazor WebAssembly

I'm trying to read a JSON file that resides in my razor class library. I've added it to the wwwroot folder that is used for static assets within the library, similar to the guidance for accessing static assets (css, js files).

I am then trying to read this file in my OnInitializedAsync() event of my blazor component like so:

protected async override Task OnInitializedAsync()
{
    MenuItems = await Http.GetFromJsonAsync<List<MenuItem>>("_content/[LibraryName]/sitemap.json");
    await base.OnInitializedAsync();
}

I have also tried it without the _content part:

protected async override Task OnInitializedAsync()
{
    MenuItems = await Http.GetFromJsonAsync<List<MenuItem>>("sitemap.json");
    await base.OnInitializedAsync();
}

Both calls end up with the following exception:

System.InvalidOperationException: An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set.

Based on the blazor wasm template, it reads the weather forecast JSON file out of the wwwroot folder within the application. I'm trying to do the same thing but using the wwwroot folder out of the class library. I can't seem to find guidance on how to achieve this. Any help is greatly appreciated.

Upvotes: 2

Views: 1646

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273449

The main error is

The request URI must either be an absolute URI or BaseAddress must be set.

And that is odd, normally the HttpClient is configured correctly in Program or Startup.

So: where does your Http come from, what did you change in the startup code? You should have something like

builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });

Upvotes: 2

Related Questions