静态类中的Asp.Net Core配置 [英] Asp.Net Core configuration in static class

查看:148
本文介绍了静态类中的Asp.Net Core配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从静态类中的appsettings.json文件读取url.我尝试过

I want to read url from my appsettings.json file within static class. I tried something like

private static string Url => ConfigurationManager.GetSection("Urls/SampleUrl").ToString();

但是每当我尝试调用 GetSection()方法时,我都会得到空值.

But whenever i try to call GetSection() method i get null value.

  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "ConnectionStrings": {
    "cs1": "some string",
    "cs2": "other string"
  },
  "Urls": {
    "SampleUrl": "google.com"
  },
  "AllowedHosts": "*"

我只是想从appsettings中读取一些数据.根据文档,我不应该以某种方式注册我的标准artsettings.json文件,因为默认情况下,Program类中的 Host.CreateDefaultBuilder(args)会对我起作用.

I simply want to read some data from appsettings. According to docs i should not somehow register my standart appsettings.json file because Host.CreateDefaultBuilder(args) in Program class does it for me by default.

推荐答案

正如所提到的

As it mentioned here, you can add static property to your Startup.cs

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

public static IConfiguration StaticConfig { get; private set; }

并在静态类中使用:

var x = Startup.StaticConfig.GetSection("whatever");

这篇关于静态类中的Asp.Net Core配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆