【问题标题】:Cannot get the value of appsettings.json in Blazor WASM无法在 Blazor WASM 中获取 appsettings.json 的值
【发布时间】:2022-10-01 02:37:45
【问题描述】:

我的“appsettings.json”中有这个

\"AllowedHosts\": \"*\",
  \"AlprReport\": {
    \"ConnectionAddress\": \"http://192.168.100.37:81/alprreport/cashdeclaration\"
  }

我试着把它放在我的 Razor 中:

public RazorComponent : ComponentBase
{
    [Inject] IConfiguration configuration;
    
    public void SomeMethod() 
    {
        var result = configuration.GetSection(\"AlprReport:ConnectionAddress\").Value
    }
}

我总是得到空值的结果。我尝试使用以下方法从我的“Program.cs”中获取它:

var alprReport = builder.Configuration.GetSection(\"AlprReport:ConnectionAddress\").Value;

我仍然无法让它工作。我在这里做错了什么?谢谢。

  • 你的 appsettings.json 文件在哪个目录?

标签: asp.net-core blazor


【解决方案1】:

检查您的appsettings.json 所在的路径。由于它是 Blazor WASM,它应该位于 wwwroot 文件夹中。

【讨论】:

  • 我处于开发模式,所以我应该能够在 wwwroot 文件夹之外获取 appsettings.json。
  • 并不真地。它应该像@Raffy 所说的那样在 wwwroot 内。
【解决方案2】:

尝试使用GetConnectionString

    "ConnectionStrings": {
    "ConnectionAddress": "http://192.168.100.37:81/alprreport/cashdeclaration"
  }
  // then the same code with injection but use instead `GetConnectionString`
  var result = configuration.GetConnectionString("ConnectionAddress");

或继续您的方式并将您的代码更改为:

configuration.GetSection("AlprReport")["ConnectionAddress"]

因为GetSection是键值方法!

【讨论】:

  • 或者干脆var result = configuration["AlprReport:ConnectionAddress"];
【解决方案3】:

看起来您在 asp.net 核心服务器上托管了一个 blazor wasm 应用程序。在这种情况下,您实际上有两个appsettings.json 文件,一个用于服务器应用程序,一个用于客户端。您可能正试图从您的客户端访问服务器的appsettings.json,但您无法访问这样的服务器文件。对于客户端,您必须在 wwwroot 文件夹中创建一个单独的 appsettings.json 文件,您也可以在文档中看到: https://docs.microsoft.com/en-us/aspnet/core/blazor/fundamentals/configuration?view=aspnetcore-6.0

如果你想从客户端访问服务器的 appsettings,你必须通过 api 公开它(如果你在配置中存储敏感数据是个坏主意)。例子:

[ApiController]
[Route("api/[controller]")]
public class InfoController : ControllerBase
{
    private readonly IConfiguration _configuration;

    public InfoController(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    [HttpGet]
    [Route("config")]
    public async Task<IActionResult> GetConfiguration()
    {
        var result = _configuration["AlprReport:ConnectionAddress"];
  
        return Ok(result);
    }
}

然后在Program.cs中,修改已有的HttpClient服务注册使用客户端读取文件:

var http = new HttpClient()
{
    BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)
};

builder.Services.AddScoped(sp => http);

using var response = await http.GetAsync("api/info/config");
using var stream = await response.Content.ReadAsStreamAsync();

builder.Configuration.AddJsonStream(stream);

Blazor App settings configuration

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-22
    • 2021-12-27
    • 1970-01-01
    • 2021-11-06
    • 1970-01-01
    • 2021-07-17
    • 2021-04-13
    • 1970-01-01
    相关资源
    最近更新 更多