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

发布于 2025-01-14 06:17:44 字数 2438 浏览 2 评论 0原文

我正在尝试在 blazor 服务器应用程序的后台服务中访问存储在 appsettings.json 文件中的数据,但大多数有关如何在线执行此操作的插图都是基于 Blazor 的 Webassemble 配置。我想我应该使用 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": "*"
}

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

等风来 2025-01-21 06:17:44

如果您正在处理某些类,例如创建服务,则需要在 construction 中添加 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 组件那么你需要像这样注入IConfiguration

using Microsoft.Extensions.Configuration;

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

你可以阅读更多关于这个

If you are working in some class for example like creating a service, you need to add IConfiguration in the constructure:

using Microsoft.Extensions.Configuration;

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

If you have a razor component then you need to Inject IConfiguration like this:

using Microsoft.Extensions.Configuration;

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

You can read more about this

很快妥协 2025-01-21 06:17:44

除了上面的解决方案之外,以下解决方案也有效:
首先安装此包:

using Microsoft.Extensions.Configuration;

然后在类的顶部添加以下代码行:

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

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

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

检查以下内容有关详细信息的链接:https://learn.microsoft.com/en-us/dotnet/core/extensions/configuration

The following solution, aside from the one above, also works:
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://learn.microsoft.com/en-us/dotnet/core/extensions/configuration

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文