读取appsettings.json文件设置始终为空。如何在 .NET 7 中做到这一点(最好的方法)?

问题描述 投票:0回答:3

我正在将项目从 .NET Core 3.1 切换到 .NET 7,但是,但我似乎无法让它工作。我认为配置已经内置到框架中(使用 Blazor),并且配置数据已经在幕后注入,因此您可以通过

 访问 
appsettings.json

文件
builder.Configuration.GetSection("MySection:MyParam").Value; 

来自

program.cs
班级。它总是返回 null,因此也许需要首先调用
builder.Build()
(通常会这样做),但我需要在构建之前从
.json
文件获取数据,以便首先定义服务。不知道如何正确执行此操作。

program.cs
文件内容:

using BlazorWASM;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;

namespace Company.WebApplication1;

public class Program
{
    public static async Task Main(string[] args)
    {
        var builder = WebAssemblyHostBuilder.CreateDefault(args);
        builder.RootComponents.Add<App>("#app");
        builder.RootComponents.Add<HeadOutlet>("head::after");

        string APIPath = builder.Configuration.GetSection("API:Path").Value; //this is coming up null

        builder.Services.AddSingleton(sp => new HttpClient { BaseAddress = new Uri(APIPath) });

        await builder.Build().RunAsync();
    }
}

这是位于

appsettings.json
(默认)文件夹中的
wwwroot
文件:

{
      "API": {
        "Path": "https://api.somewebsite.com/"
      },
      "ConnectionStrings": {
        "DefaultConnection": "Server=localhost;Database=_CHANGE_ME;Trusted_Connection=True;"
      }
}

有什么想法吗?我知道我做错了,但是必须有一百种不同的方法来访问

appsettings.json
文件,但是,希望看到最佳实践方法(实际上有效)。

.net-core blazor-webassembly appsettings .net-7.0
3个回答
1
投票

令我惊恐的是,我发现您无法从 Blazor WASM 读取文件。执行此操作的唯一方法是创建一个服务并让它使用 httpclient 从单独的服务器获取配置数据。
虽然有问题的应用程序目前已硬编码为使用其他 API,但目前它工作正常,但如果任何其他 APi 端点发生更改(许多是第 3 方),则该应用程序的用户将必须下载该应用程序的新副本或者我需要创建一个公共 API,其 URI 被硬编码到应用程序本身中,然后可以快速更改第 3 方 API URI(通过每次应用程序启动时上传配置设置)。 当我想起来的时候,这是一个愚蠢的问题。


0
投票

但我需要在构建之前从 .json 文件获取数据,以便首先定义服务。

您可以使用选项模式
我想说你需要它的某种用法:

  1. 为您的设置创建类。

         public class CustomSettings
         {
             public static string SectionName = nameof(CustomSettings);
    
             public string FirstService { get; set; }
    
             public string SecondService { get; set; }
         }
    
  2. 将匹配部分添加到配置文件中。

    {
      "CustomSettings": {
        "FirstService": "http://localhost:8090",
        "SecondService": "http://localhost:8091"
      }
    }
  1. 并使用 IConfiguration 对象的 API 进行绑定:
 var settings = app.Configuration.GetSection(CustomSettings.SectionName)
                   .Get<CustomSettings>();

应该可以。干杯!

PS:在第三阶段你想使用

builder.Configuration...
代替
app.Configuration
,它也可以工作。


0
投票

只要您将 S3 存储桶设置为公开,您仍然可以读取其中的任何内容,所以我只是读取它。

我使用了一个假设,您可以根据需要进行更改,但使用以下代码。

//Not the best assumption, but here we go
if (!builder.HostEnvironment.BaseAddress.Contains("localhost"))
{
    using var httpClient = new HttpClient();
    httpClient.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress);
    var jsonStream = await httpClient.GetStreamAsync("/appsettings.json");
    builder.Configuration.AddJsonStream(jsonStream);
}
© www.soinside.com 2019 - 2024. All rights reserved.