c# - Blazor 应用程序/Razor 中的 IConfiguration 始终为 NULL .NET CORE

标签 c# asp.net-core razor configuration blazor

无论我尝试什么,IConfiguration 始终为 null.. 我也尝试将单例添加到启动类,但始终为 null...

启动类

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

这是我的安全类

        IConfiguration _configuration { get;} **<<always null**
        public Security(IConfiguration configuration) **<<always null**
        {
            _configuration = configuration;
        }
         public  string GetConnectionString()
        {
            string connectionString = _configuration.GetConnectionString("localDb");
            return connectionString;

        }

这是我的 Index.Razor 页面

 namespace WebbiSkoolsQuizManager.Pages
{
    public class IndexBase : ComponentBase
    {
        public IConfiguration Configuration { get; }
        public async Task TryLogin(string user, string pass)
        {
            
        }
       
         

        public async Task AddUserHash(string username, string password)
        {
            Security secure = new Security(Configuration);
            string connectionstring = secure.GetConnectionString();
            
            
        }
    }
}

Appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "ConnectionKeys": {
    "localDb": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Quiz;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"

  },
  "AllowedHosts": "*"
}

提前谢谢你,我搜索了很多,关于 blazor 特定的修复,但我找不到任何东西..(P.S 它的 .Net 核心 3)

最佳答案

我猜是这样的:public IConfiguration Configuration { get; }

应该是:

[Inject]
public IConfiguration Configuration { get; }

注意:您不能简单地定义服务的属性,并期望它被填充...如果您像您的情况一样使用 Razor 组件类定义 (.cs),则可以注入(inject)服务通过使用 [Inject] 属性。如果您使用的是 Razor 组件 (.razor),您可以在组件的 View 部分使用 @inject 指令,例如:

@page "/"
@inject IConfiguration Configuration

或者在 @code 部分,像这样:

@code
{
    [Inject]
    public IConfiguration Configuration { get; }

}

另请注意,如果您想将服务注入(inject)普通 C# 类,则需要使用构造函数注入(inject)

关于c# - Blazor 应用程序/Razor 中的 IConfiguration 始终为 NULL .NET CORE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65958238/

相关文章:

c# - 如何将 .xproj 引用到 .csproj 中?

asp.net-mvc - 使用 Ajax.BeginForm 显示验证摘要

c# - 如何从 NuGet 包获取的 RCL 导入 Razor 页面?

c# - 在 ASP.NET 中第一次单击时按钮 OnClick 没有触发?

c# - 获取光标相对于控件的位置 - C#

c# - 尝试激活时无法解析类型 'Microsoft.AspNetCore.Mvc.IUrlHelper' 的服务

asp.net-mvc - DropDownListFor SelectedItem 的问题

c# - 将 List<object> 转换为 List<Type>,类型在运行时已知

c# - 在 C# 中查找两个列表之间的重叠

asp.net-core - 启动 IIS Express 以运行 ASP.NET Core 应用程序