Blazor WASP App (ASP.NET Core Hosted) Trying to get a setting value from my appsettings.json file

477 Views Asked by At

I am having troubles trying to get a setting from my appsettings.json file. I put a setting for a local path named: FileStorage. Here are my files:

My appsettings.json file:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },

  "AllowedHosts": "*",
  "FileStorage": "D:\\Temp\\Storage"
}

My razor page:

@page "/"
@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration
<h3>Configuration</h3>
<h4>File Storage: @Configuration["FileStorage"]</h4>

My Program.cs file (server project):

var builder = WebApplication.CreateBuilder(args);
builder.Configuration.SetBasePath(Directory.GetCurrentDirectory());
builder.Configuration.AddJsonFile(
"appsettings.json", optional: true, 
reloadOnChange: true);

I have been trying many ways and still get a NULL value for FileStorage setting. What am I doing wrong?

1

There are 1 best solutions below

4
Mister Magoo On

First a quick note - Blazor WebAssembly runs in the browser sandbox and does not use the local FileSystem (you can through JavaScript and the browser's FileSystem Apis, but that is another story), so your use of GetCurrentDirectory and any plans you have for the FileStorage setting need to take that into account.

Now, you don't need to write any code to load appsettings.json in Blazor WebAssembly - it is loaded by default, so remove this code:

builder.Configuration.SetBasePath(Directory.GetCurrentDirectory());
builder.Configuration.AddJsonFile("appsettings.json", optional: true, 
  reloadOnChange: true);

Your value should be populated by default.

If you want to check the configuration is loaded, this code will list all keys/values:

<article>
    <h2>Configuration</h2>
    <ul>
        @foreach (var item in Configuration.AsEnumerable())
        {
            <li>@item.Key: @item.Value</li>
        }
    </ul>
</article>