如何在 Blazor 服务器中访问 appsettings.json 数据

How to access appsettings.json data in Blazor Server

我试图在我的 Blazor 服务器应用程序的后台服务中访问存储在 appsettings.json 文件中的数据,但大多数关于如何在线执行此操作的说明都是基于 Blazor 的 Webassembly 配置。我想我应该使用 Microsoft.Extensions.Configuration 包,但我不太清楚如何实现它。

下面是后台服务和关键代码

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();
            }
        }

    }
}

我想使用 appsetting.json 中定义的 connectionString 并用它来设置 HandleTimer() 方法中的 connectionString 变量。

下面是appsettings.json文件

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

任何详细的指导将不胜感激。

如果您在某些 class 中工作,例如创建服务,您需要在 constructure:

中添加 IConfiguration
using Microsoft.Extensions.Configuration;

private readonly IConfiguration configuration;
public PeriodicExecutor(IConfiguration configuration)
{             
 this.configuration = configuration;
}
 //Then you can use it 
var connection=  configuration["connectionString"];

如果你有一个 razor 组件,那么你需要 Inject IConfiguration 像这样:

using Microsoft.Extensions.Configuration;

[Inject]
private IConfiguration configuration { get; set; }
//then you can get your connectionString
var connection=  configuration["connectionString"];

您可以阅读更多关于 this

除上述解决方案外,以下解决方案也有效: 首先安装这个包:

using Microsoft.Extensions.Configuration;

然后在class的顶部添加下面一行代码:

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

然后您可以使用密钥访问存储的数据,如下所示:

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

查看以下 link 了解更多信息:https://docs.microsoft.com/en-us/dotnet/core/extensions/configuration