EResman
EResman

Reputation: 444

Access appsettings.json from .NET 4.5.2 project

I have two projects, a 1.1.0 ASP.NET Core project and a reference to a 4.5.2 project.

I want to get values from the appsettings.json file to my 4.5.2 project. The appsettings.json file is in the core project.

Tried this from my 4.5.2 project with no luck:

var mailServer = ConfigurationManager.AppSettings["MailServer"];

How can I access the values from my 4.5.2 project?

Upvotes: 20

Views: 23099

Answers (3)

Pablo Salcedo
Pablo Salcedo

Reputation: 348

Nicely done "Johann Medina", but you forgot to explain a little bit your solution in order people can understand better the idea. I have done it the same way, but here it's the full explanation in order to use it this way...

appsetting.JSON example:

{
    "Email": {
        "Host": "smtp.office365.com",
        "Port": "587",
        "From": "[email protected]",
        "Username": "[email protected]",
        "Password": "IsAAbbUaa22YTHayTJKv44Zfl18BClvpAC33Dn5p4s="
    }
}

POCO class example:

namespace AppSettingsTest
{
    public class AppSettings
    {
        public Email Email { get; set; }
    }

    public class Email
    {
        public string Host { get; set; }
        public int Port { get; set; }
        public string From { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
    }
}

Getting appsetting.JSON content example:

    using (var reader = new StreamReader(Directory.GetCurrentDirectory() + "/appsettings.json")) {
        var appSettings = JsonConvert.DeserializeObject<AppSettings>(reader.ReadToEnd());
    }

NOTE: Just make sure to set "Copy always" in the property option "Copy to Output Directory" to the JSON file.

Happy Coding!

Upvotes: 10

iojancode
iojancode

Reputation: 618

what about this?

using (var reader = new StreamReader(Directory.GetCurrentDirectory() + "/appsettings.json"))
    Settings = JsonConvert.DeserializeObject<Settings>(reader.ReadToEnd());

Upvotes: 1

Set
Set

Reputation: 49819

ConfigurationManager works with XML-based configuration files that have specific format and doesn't know how to read the custom JSON file.

Cause you use appsettings.json for the ASP.NET Core project as well, you may add dependencies to Microsoft.Extensions.Configuration and Microsoft.Extensions.Configuration.Json packages and read settings using ".NET Core approach":

var builder = new ConfigurationBuilder()
              .AddJsonFile(@"<path to appsettings.json>");

var configuration = builder.Build();
//  configuration["MailServer"]

Of course, as appsettings.json is a simple JSON file, you may always directly deserialize using any JSON provider.

Upvotes: 17

Related Questions