首页 > 解决方案 > 在 blazor 客户端中放置配置文件的位置

问题描述

我有一个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;}
}

开拓者形式

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

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

我想我需要以某种方式Config解决这个问题。Startup

标签: c#configurationrootblazorconfiguration-files

解决方案


这与“位置”无关,所有文件都与 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


推荐阅读