在ASP.NET Blazor中读取静态文件 [英] Reading static files in ASP.NET Blazor
问题描述
我有一个客户端Blazor应用程序.我想要一个用于客户端配置的 appsetting.json
文件,就像我们在其中的 environment.ts
角度的.
为此,我在 wwwroot
下保留了一个 ConfigFiles
文件夹,并在其中包含一个JSON文件.我正在尝试按以下方式读取此文件.
首先获取路径:
公共静态类ConfigFiles{公共静态字符串GetPath(string fileName){返回Path.Combine("ConfigFiles",fileName);}}
比看它:
公共字符串GetBaseUrl(){字符串T = string.Empty;尝试{T = File.ReadAllText(ConfigFiles.GetPath("appsettings.json"));}抓住(前例外){T = ex.Message;}返回T;}
但我总是会收到错误消息:
找不到路径"/ConfigFiles/appsettings.json"的一部分.
在 GetPath()
方法中,我也尝试过:
返回Path.Combine("wwwroot/ConfigFiles",fileName);
但是我仍然遇到相同的错误:
找不到路径"wwwroot/ConfigFiles/appsettings.json"的一部分.
由于客户端Blazor中没有 IHostingEnvironment
的概念,因此在此处读取静态JSON文件的正确方法是什么?
我有一个客户端Blazor应用程序
好的,这意味着 File.ReadAllText(...)
和 Path.Combine(...)
根本不起作用.客户端意味着您可以在Android或Mac-OS或任何其他版本上运行.
Blazor团队以FetchData示例页面的形式为您提供了有关如何读取文件的完整示例.
forecasts =等待Http.GetJsonAsync< WeatherForecast []>("sample-data/weather.json");
这将为您获取 wwwroot/sample-data
中文件的内容如果需要AllText,可以使用 Http.GetStringAsync(...)
如果要按用户设置,请查看Blazored.LocalStorage程序包.
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 IHostingEnvironment
in client-side Blazor, what is the correct way to read a static JSON file here?
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.
这篇关于在ASP.NET Blazor中读取静态文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!