Reading static files in ASP.NET Blazor

一曲冷凌霜 提交于 2021-01-27 12:21:53

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/58110347/reading-static-files-in-asp-net-blazor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!