【问题标题】:Where to place config file in blazor client在 blazor 客户端中放置配置文件的位置
【发布时间】:2019-12-08 16:44:42
【问题描述】:

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

【问题讨论】:

    标签: c# configuration root blazor config-files


    【解决方案1】:

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

    【讨论】:

    • 我有多个 blazor 组件使用使用 json 文件构建的服务。我无法在 Startup 中创建此服务吗?在我初始化我的 blazor 组件之前,我基本上需要阅读json
    • 不,您可以在 Configure() 中获取 HttpClient,但调用它会挂起应用程序,我认为因为它需要 .Result。我们需要一个 ConfigureAsync() 。据我所知,在 ConfigureServices() 中获取它不是一个选项。
    • 那么,您在 Startup 中需要它的难度有多大?通常可以延迟加载东西直到第一次使用。
    • 好吧,我有几个Components,其中一些是html forms,我将action 属性绑定到某个配置值。我从一开始就真的需要它们。我已经更新了我的最初的帖子。
    • 用户机器上的任何其他软件是否可以轻松访问它?
    猜你喜欢
    • 2022-01-27
    • 2017-10-23
    • 2020-07-27
    • 1970-01-01
    • 2011-01-15
    • 2013-04-26
    • 1970-01-01
    • 2013-01-22
    • 2019-04-30
    相关资源
    最近更新 更多