Home > Enterprise >  How to access appsettings.json data in Blazor Server
How to access appsettings.json data in Blazor Server

Time:03-15

I am trying to access the data stored in the appsettings.json file in a background service in my blazor server app but most illustrations of how to do this online are based on the Webassembly configuration of Blazor. I think I'm suppossed to use the Microsoft.Extensions.Configuration package but I can't quite figure out how to implement it.

Below is the background service with the essential code

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using System.Timers;
using log4net;
using System.Net;
using System.IO;
using System.Data.SqlClient;
using Microsoft.Extensions.Configuration;

namespace BlazorServerApp
{
    public class JobExecutedEventArgs : EventArgs { }
    public class PeriodicExecutor : IDisposable
    {
        Timer _Timer;
        bool _Running;

        public void StartExecuting()
        {
            if (!_Running)
            {
                // Initiate a Timer
                _Timer = new Timer();
                _Timer.Interval = 5000;
                _Timer.Elapsed  = HandleTimer;
                _Timer.AutoReset = true;
                _Timer.Enabled = true;

                _Running = true;
            }
        }
        void HandleTimer(object source, ElapsedEventArgs e)
        {
            // Execute required job
            //connect to the appropriate SQL database
            var connectionString = "connection";
            //create connection variables for the two main SQL operations we will be doing
            using var connectionUpdate = new SqlConnection(connectionString);
            using var connectionCreate = new SqlConnection(connectionString);
            while (true)
            {
                Parallel.Invoke(
                () => createSurveyQueueEntries(connectionCreate),
                () => updateSurveyQueue(connectionUpdate));
            }
            // Notify any subscribers to the event
            OnJobExecuted();
        }
        public void Dispose()
        {
            if (_Running)
            {
                _Timer?.Dispose();
            }
        }

    }
}

I would like to take the connectionString defined in appsetting.json and use it to set the connectionString variable in the HandleTimer() method.

Below is the appsettings.json file

{
  "connectionString": "connection",
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

Any detailed guidance would be greatly appreciated.

CodePudding user response:

You need to Inject IConfiguration like this:

[Inject]
private IConfiguration Config { get; set; }

then you can get your connectionString:

var connection=  Config ["connectionString"];

You can read more about this

CodePudding user response:

The following worked for me: First install this package:

using Microsoft.Extensions.Configuration;

Then add the following line of code at the top of the class:

private static readonly IConfiguration config = new ConfigurationBuilder().AddJsonFile("appsettings.json").AddEnvironmentVariables().Build(); 

And then you can access the stored data using the key like so:

var connectionString = config.GetValue<string>("keyname");

Check the following link for more information: https://docs.microsoft.com/en-us/dotnet/core/extensions/configuration

  • Related