配置文件在blazor客户端中的放置位置

时间:2019-07-31 08:10:22

标签: c# configuration root blazor config-files

我有一个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应用程序的当前目录以便检索Client项目的配置?

更新

用法
我有几种html表单,其中将一些action之类的html属性绑定到一些配置文件值:

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;}
}

我认为我需要以某种方式在Config中解决此Startup

1 个答案:

答案 0 :(得分:2)

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