Main Page
 The gatekeeper of reality is
 quantified imagination.

Stay notified when site changes by adding your email address:

Your Email:

Bookmark and Share
Email Notification
.Net CORE and AppSettings
Purpose
The purpose of this tutorial is to show how a variety of ways with which you can read data in an appsettings.json file in .Net CORE C#. Unlike .Net Framework, there is additional overhead with .Net CORE so this page could be good to have as a reference.

Appsettings.json Examples:

{
	"ConnectionStrings": {
		"keyname": "Server=someserver;Database=somedatabase;User ID=someid;Password=somepassword"
	},
	"ApplicationVersion": "0.9",
	"data": {
		"url": "http://somesite.com"
	}
}


Startup.cs:

using Microsoft.Extensions.Configuration;

public class Startup
{
	public IConfiguration Configuration { get; }
	public Startup(IConfiguration configuration)
	{
		/* Database Connection String Retrieval */
		Configuration = configuration;
		SqlHelperForDBConnections.dbconnectdetail = ConfigurationExtensions.GetConnectionString(this.Configuration, "keyname");
		/* Version Retrieval */
		RetrieveKeyValuePairHelper.applicationVersion = Configuration["ApplicationVersion"];
		/* Other Key Value Retrieval */
		RetrieveKeyValuePairHelper.dataUrl = Configuration["data:url"];
	}
}


Helper Methods:

public class SqlHelperForDBConnections
{
	public static dbconnectdetail;
	/* Method used in other parts of the application to retrieve the DB connection */
	public static SqlConnection GetDBConnection()
	{
		try {
			SqlConnection connection = new SqlConnection(dbconnectdetail);
			return connection;
		} catch (Exception e) {
			throw;
		}
	}
}
public class RetrieveKeyValuePairHelper
{
	public static string applicationVersion;
	/* Method used in other parts of the application to retrieve the version */
	public static string GetApplicationVersion()
	{
		return applicationVersion;
	}
	public static string dataUrl;
	/* Method used in other parts of the application to retrieve the data url */
	public static string GetDataUrl()
	{
		return dataUrl;
	}
}


About Joe
Find Out Now!