gpt4 book ai didi

c# - 在 Blazor 客户端中放置配置文件的位置

转载 作者:行者123 更新时间:2023-11-30 16:37:44 27 4
gpt4 key购买 nike

我有一个 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)绑定(bind)到一些配置文件值:

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

最佳答案

这与“位置”无关,所有文件都与 wwwroot 相关,例如图像等。

但这与您如何阅读文件有关。 File.ReadAllText() 可能会抛出错误,浏览器不支持它。

您可以借鉴/fetchdata 示例页面:使用 HttpClient。

我制作了一个示例,但我无法在 Startup 类中使用任何东西。我想重要的部分(比如 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

关于c# - 在 Blazor 客户端中放置配置文件的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57286093/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com