Blazor requesting a json file

Viewed 4969

I am trying to retrieve data from the server. But I can't get the json file from the server. I placed my json file in wwwroot/data/Users.json. This is my code. I receive this exception: Unhandled exception rendering component: Could not find a part of the path "/data/Users.json".

@page "/"

@code{
    public class User
    {
        public string username;
        public string password;
    }
}
@{ 
    string json = System.IO.File.ReadAllText("data/Users.json");
    User mahan = Newtonsoft.Json.JsonConvert.DeserializeObject<User>(json);

<body>
    <h1>Usernsme: @mahan.username</h1>
</body>
1 Answers

In Blazor Server you can use File.ReadAllText("wwwroot/data/Users.json");

In Blazor WebAssembly you don't provide the wwwroot/ part but since File.ReadAllText() is not supported there it doesn't really matter.

Under WebAssembly you can await Http.GetStringAsync("data/Users.json");

Check FetchData.razor and weather.json for a full example.

Related