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

Sau*_*abh 4 asp.net-core blazor asp.net-core-3.0 .net-core-3.0 blazor-client-side

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

为此,我在其中保留了一个ConfigFiles文件夹wwwroot和一个 JSON 文件。我正在尝试阅读此文件,如下所示。

首先获取路径:

public static class ConfigFiles
{
    public static string GetPath(string fileName)
    {
        return Path.Combine("ConfigFiles", fileName);
    }
}
Run Code Online (Sandbox Code Playgroud)

比阅读它:

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

但我总是收到错误:

找不到路径“/ConfigFiles/appsettings.json”的一部分。

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

return Path.Combine("wwwroot/ConfigFiles", fileName);
Run Code Online (Sandbox Code Playgroud)

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

找不到路径“wwwroot/ConfigFiles/appsettings.json”的一部分。

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

Hen*_*man 6

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

OK,这意味着File.ReadAllText(...)Path.Combine(...)在所有不打算工作。客户端意味着您可以在 Android 或 Mac-OS 或其他任何系统上运行。

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

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

这会让你得到一个文件的内容如果你想要 AllTextwwwroot/sample-data
你可以使用Http.GetStringAsync(...)

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

  • 非常感谢您的 GetStringAsync! (3认同)