C#获取appsettings.json值并将其存储到app.config .netcore 2.0中

时间:2018-11-14 14:14:53

标签: c# asp.net

我在我的appsettings.json文件中有一个值,我想在我的appinsight.config文件中使用它。

这是否容易实现,或者会变得过于复杂?我对c#不太熟悉(对于powershell来说还可以)

到目前为止,这是我的设置: appsettings.json

<?xml version="1.0" encoding="utf-8"?>
<ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings">
  <InstrumentationKey>appsettingskey</InstrumentationKey>

appinsight.config

        var config = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("config/hosting.json", optional: true)
            .AddCommandLine(args)
            .Build();

和主要部分:

public static void main (String[] args) throws java.lang.Exception
{   
    class Print {
        public String name = "Timur";
        private void writeObject() {
            System.out.println(name);
        }
    }
    class Write {
        public void callPrint(Print p) {
            p.writeObject();
        }
    }
    Print p = new Print();
    Write w = new Write();
    w.callPrint(p);
}

我还挺新的,还在学习,所以请耐心

2 个答案:

答案 0 :(得分:2)

如果您希望遥测记录到应用程序见解,就足以将值存储在 Microsoft.ApplicationInsights.AspNetCore 包的appsettings.json中以获取值

{
  "ApplicationInsights": {
    "InstrumentationKey": "11111111-2222-3333-4444-555555555555"
  }
}

然后将json添加到构建器

.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)

Here's很好的演练

答案 1 :(得分:1)

您可以通过配置映射来获取配置文件的值。 以下是我在NETCORE环境中的使用方式,可以作为参考,如果您使用的是netframework,则其配置可能会有所不同。

1。配置环境

安装: Microsoft.Extensions.Options.ConfigurationExtensions

2。配置appsetting.json 在appsetting.json中配置映射类的JSON节点。

{
  "AppKeys": {
    "AppKey": "2"
  }
}

3。新的映射类,将您的配置结构映射到类属性

 public class AppKeys
    {
        public string AppKey{ get; set; }
    }

4。添加配置映射

public void ConfigureServices(IServiceCollection services)
{
   services.AddOptions();
   services.Configure<AppKeys>(Configuration.GetSection("AppKeys"));
}

5。使用访问值,例如:

var key = Configuration["AppKeys:AppKey"]

6。使用DI注入进行配置

public class name
{   
    private readonly AppKeys classname;   
    public RedisClient(IOptions<AppKeys> value)
    {
         classname = value.Value;
    }
}
相关问题