在Blazor客户端中放置配置文件的位置在哪里?

4

我有一个基于浏览器的 Blazor 项目,我正在尝试使用配置文件 json 来设置一些内容。但是我不知道将这个配置文件放在哪里以便后续使用。

发布时的文件夹结构如下:

-root  //tried placing the json here
  - [Blazor server's dll's]
  - Client
    -dist   //tried placing the json here
      -framework/
      -css/
      -index.html

客户端

public class Startup {
        public static Config config;
        public static Action<IServiceCollection> ConfigureServicesForDebugging { get; set; }
        public void ConfigureServices(IServiceCollection services) {
            ConfigureServicesForDebugging?.Invoke(services);
            services.AddSingleton<AdminService>();
            Console.WriteLine(Directory.GetCurrentDirectory()); //renders /
            var config = File.ReadAllText("conf.json");

        }

        public void Configure(IBlazorApplicationBuilder app) {
            app.AddComponent<App>("app");
        }
    }

我希望能够在Client项目内读取配置文件,但是我不知道该如何操作。无法找到它。
我尝试打印并查看Console.WriteLine(Directory.CurrentDirectory),但只得到相对路径。

如何找到我的Blazor应用程序的当前目录以检索客户端项目的配置?

更新

使用方法
我有几个HTML表单,在其中绑定一些HTML属性(如action)到某个配置文件值:

class Config
{
   public string FormUrl{get;set;}
}

Blazor表单

<form action=config.FormUrl>
<input type="submit">Submit</button>
</form>

@functions()
{
   [Parameter] protected Config config{get;set;}
}

我猜我需要在Startup中解析这个Config
1个回答

3

这并不是关于“where”的问题,所有文件都与wwwroot相关,例如图片等。

但它关乎你如何读取文件。File.ReadAllText()可能会抛出异常,在浏览器中不被支持。

你可以从/fetchdata示例页面学习:使用HttpClient。

我设计了一个示例,但我无法在启动类中使其正常工作。我想必要的部分(如HttpClient)尚未配置好。

所以你可以从主页读取配置,或者在App.razor中实现它:

@inject HttpClient Http

<Router AppAssembly="typeof(Program).Assembly">
    <NotFoundContent>
        <p>Sorry, there's nothing at this address.</p>
    </NotFoundContent>
</Router>

@code
{
    protected override async Task OnInitAsync()
    {            
        string json = await Http.GetStringAsync("/conf.json");
        Console.WriteLine(json);            
    }
}

这里读取的是 wwwroot/conf.json 文件


我有多个 Blazor 组件,它们使用一个服务,该服务是使用 json 文件构建的。我是否无法在 Startup 中创建此服务?基本上,我需要在初始化我的 Blazor 组件之前读取 json - Bercovici Adrian
不,你可以在Configure()中获取HttpClient,但调用它会挂起应用程序,我认为是因为它需要.Result。我们需要一个ConfigureAsync()。据我所知,在ConfigureServices()中获取它不是一个选项。 - H H
那么,在创业公司中,你需要多努力呢?通常可以将加载的内容延迟到第一次使用时再进行。 - H H
我有几个“组件”,其中一些是“HTML表单”,我将“action”属性绑定到某些配置值。我真的需要从一开始就使用它们。我已经更新了我的初始帖子。 - Bercovici Adrian
这个能被用户机器上的其他软件轻松访问吗? - Owen Johnson
看起来现在的方法是OnInitializedAsync而不是OnInitAsync。有人知道这样做配置是否是最佳实践吗? - inliner49er

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接