Search code examples
asp.net-coreblazorhttpclienturi

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.


Solution

  • 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