在 ASP.NET Blazor 中读取静态文件

Reading static files in ASP.NET Blazor

我有一个客户端 Blazor 应用程序。我想为我的客户端配置提供一个 appsetting.json 文件,就像我们在中有一个 environment.ts Angular.

为此,我在 wwwroot 下保留了一个 ConfigFiles 文件夹,并在其中保留了一个 JSON 文件。我正在尝试按如下方式阅读此文件。

首先获取路径:

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

阅读比:

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

但我总是得到错误:

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

里面的GetPath()方法,我也试过:

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

但我仍然得到同样的错误:

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

由于客户端Blazor中没有IHostingEnvironment的概念,这里读取静态JSON文件的正确方法是什么?

I have a client side Blazor Application

好的,这意味着 File.ReadAllText(...)Path.Combine(...) 根本不起作用。 客户端意味着你可以 运行 在 Android 或 Mac-OS 或其他什么。

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

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

这会为您提供 wwwroot/sample-data
中的文件内容 如果你想要 AllText

,你可以使用 Http.GetStringAsync(...)

如果你想要每个用户的设置然后查看 Blazored.LocalStorage 包。