Blazor: An invalid request URI was provided when using GetFromJsonAsync from wwwroot json file

While taking the code from the sample webassembly template, and applying it the server app, I am attempting to read in a json file located in the wwwroot directory:

{
    forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>("sample-data/weather.json");
}

Doing so I receive, “An invalid request URI was provided”, so changing it to use the http://localhost address works, but I’m trying to wrap my head around why I cannot simply provide the relative path as shown above.

  • When providing a relative URI, it will be combined with HttpClient.BaseAddress. You should check this value.

    – 

  • When I add the BaseAddress to get the file:// path, I am now receiving a new error, “The ‘file’ scheme is not supported.”. Is there something I need to add to the HttpClient to allow json files?

    – 

  • This is not a function to get into the local files system, you said it was located on wwwroot. Keep going through an http uri if you want to keep using this method.

    – 




I reproduced your issue in my side.

enter image description here

The exception showed we had a invalid url, and the relative part must be correct, so I tried to check the base url. Like you can see, in the web assembly project, it’s the localhost url.

enter image description here

But in the blazor server app, we failed to get the base url. It’s null.

enter image description here

So I add builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri("https://localhost:7058/") }); in Program.cs like what the wsam project do.

Test result like this. I create a new server project this time.
enter image description here

Leave a Comment