Home > front end >  Cannot get the value of appsettings.json in Blazor WASM
Cannot get the value of appsettings.json in Blazor WASM

Time:08-24

I have this in my "appsettings.json"

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

I tried getting it in my Razor as so:

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

I always get null value on result. I tried getting it from my "Program.cs" using this:

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

Still I cannot get it to work. What am I doing wrong here? Thanks.

CodePudding user response:

Check the path where your appsettings.json is located. Since it's Blazor WASM, it should be inside the wwwroot folder.

CodePudding user response:

Try using 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");

Or continue your way and change your code to :

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

because GetSection is a key value method!

CodePudding user response:

It looks like you have a blazor wasm application hosted on asp.net core server. In this scenario you actually have two appsettings.json files, one for the server application and one for the client. You are probably trying to access server's appsettings.json from your client but you can't access server files like that. For the client you have to create a separate appsettings.json file located inside wwwroot folder as you can also see in the documentaion: https://docs.microsoft.com/en-us/aspnet/core/blazor/fundamentals/configuration?view=aspnetcore-6.0

If you want to access server's appsettings from client you have to expose it via an api (bad idea if you store sensitive data in configuration). Example:

[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);
    }
}
  • Related