3

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?

4

1 回答 1

7

我有一个客户端 Blazor 应用程序

好的,这意味着File.ReadAllText(...)并且Path.Combine(...)根本不会工作。客户端意味着您可以在 Android 或 Mac-OS 或其他任何设备上运行。

Blazor 团队以 FetchData 示例页面的形式为您提供了如何读取文件的完整示例。

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

这将为您获取文件的内容,如果您想要 AllText ,wwwroot/sample-data
您可以使用Http.GetStringAsync(...)

如果您想拥有每个用户的设置,请查看 Blazored.LocalStorage 包。

于 2019-09-26T07:17:20.380 回答