Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading static files in ASP.NET Blazor

I have a client side Blazor Application. I want to have an appsetting.json file for my client-side configuration like we have an environment.ts in Angular.

For that, I am keeping a ConfigFiles folder under wwwroot and a JSON file inside of it. I am trying to read this file as below.

First get the path:

public static class ConfigFiles
{
    public static string GetPath(string fileName)
    {
        return Path.Combine("ConfigFiles", fileName);
    }
}

Than read it:

public string GetBaseUrl()
{
    string T = string.Empty;
    try
    {
        T = File.ReadAllText(ConfigFiles.GetPath("appsettings.json"));
    }
    catch (Exception ex)
    {
        T = ex.Message;
    }
    return T;
}

But I always get the error:

Could not find a part of the path "/ConfigFiles/appsettings.json".

Inside the GetPath() method, I also tried:

return Path.Combine("wwwroot/ConfigFiles", fileName);

But I still get the same error:

Could not find a part of the path "wwwroot/ConfigFiles/appsettings.json".

Since there is no concept of IHostingEnvironmentin client-side Blazor, what is the correct way to read a static JSON file here?

like image 649
Saurabh Avatar asked Jan 26 '23 19:01

Saurabh


1 Answers

I have a client side Blazor Application

OK, That means that File.ReadAllText(...) and Path.Combine(...) are not going to work at all. Client-side means that you could be running on Android or Mac-OS or whatever.

The Blazor team provides you with a complete sample of how to read a file, in the form of the FetchData sample page.

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

this gets you the contents of a file in wwwroot/sample-data
You can use Http.GetStringAsync(...) if you want AllText

If you want to have per-user settings then look into the Blazored.LocalStorage package.

like image 127
Henk Holterman Avatar answered Feb 27 '23 02:02

Henk Holterman