user3622142
user3622142

Reputation: 370

C# grab appsettings.json value and store into app.config .netcore 2.0

I have my a value in my appsettings.json file which I want to use in my appinsight.config file.

Is this easily possible or would it be overcomplicated? I'm not too familiar with c# (im just ok with powershell)

Here is my settings so far: appsettings.json

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

appinsight.config

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

and the main part:

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

I am quite newby and still learning, so please be patient with me

Upvotes: 0

Views: 904

Answers (2)

MagicalConch
MagicalConch

Reputation: 34

You can get the value of the configuration file by configuring the map. The following is my way of using in NETCORE environment, you can make reference,If you are using netframework, it may be configured differently.

1.Configuration environment

install: Microsoft.Extensions.Options.ConfigurationExtensions

2.To configure appsetting.json Configure the JSON node of your mapping class in appsetting.json.

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

3.New mapping class, mapping your configuration structure to class properties

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

4.Add configuration mapping

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

5.Using access value,For instance:

var key = Configuration["AppKeys:AppKey"]

6.Using DI injection to get configuration

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

Upvotes: 1

Marcus H&#246;glund
Marcus H&#246;glund

Reputation: 16801

If you want the telemetry to log to application insights it's enough to store the value in the appsettings.json for the Microsoft.ApplicationInsights.AspNetCore package to get the value

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

Then add the json to the builder

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

Here's a great walkthrough

Upvotes: 2

Related Questions