【问题标题】:Read appsettings.json from a class in .NET Core 2从 .NET Core 2 中的类中读取 appsettings.json
【发布时间】:2018-05-05 08:31:10
【问题描述】:

我需要从业务类中的appsettings.json 文件(部分:placeto)中读取属性列表,但我无法访问它们。我需要公开这些属性。

我将文件添加到Program 类中:

这是我的appsettings.json

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "placeto": {
    "login": "fsdfsdfsfddfdfdfdf",
    "trankey": "sdfsdfsdfsdfsdf"
  }
}

【问题讨论】:

  • 这个来自 MS 的文档解释了它如何 => docs.microsoft.com/en-us/aspnet/core/fundamentals/…
  • 但我需要在自定义类中阅读,示例在控制器中,我尝试了几个选项。在 .Net 标准中使用 `string userName = System.Configuration.ConfigurationManager.AppSettings["PFUserName"];` 来读取 web.config,在 .Net 核心中相当于 @CodeNotFound
  • 我链接你的答案展示了如何在课堂上使用appsettings.json。在这种情况下是LocalMailService,但它可以是你想要的任何东西。

标签: c# asp.net-core-2.0 appsettings


【解决方案1】:

首先:使用program.cs 中的默认值,因为它已经添加了配置:

public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
}

第二:为您的类创建一个接口,并通过创建Iconfiguration 字段通过依赖注入传递配置:

private readonly IConfiguration Configuration;

然后由构造函数传递:

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

然后为您的类创建一个接口,以便正确使用Dependency Injection。然后可以创建它的实例,而无需将IConfiguration 传递给它。

这是类和接口:

using Microsoft.Extensions.Configuration;

namespace GetUserIdAsyncNullExample
{
    public interface ITest { void Method(); }

    public class Test : ITest
    {
        public Test(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        private readonly IConfiguration Configuration;
        public void Method()
        {
            string here = Configuration["placeto:login"];
        }
    }
}

第三:然后在你的 startup.cs 中通过调用为你的类实现依赖注入:

services.AddSingleton< ITest, Test>();

在您的 ConfigureServices 方法中

现在您也可以将您的类实例传递给依赖注入使用的任何类。


例如,如果您有 ExampleController 并希望在其中使用您的课程,请执行以下操作:

 private readonly ITest _test;

 public ExampleController(ITest test) 
 {
     _test = test;          
 } 

现在你有 _test 实例可以在你的控制器的任何地方访问它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多