Advertisements

Adding A Configuration Source File In ASP.NET Core 1.0


Introduction

In this article, I will explain how to add a configuration source in ASP.NET Core 1.0. This is the simplest way to access the JSON file information in ASP.NET Core 1.0.

Before reading this article, you must read the articles given below for ASP.NET Core knowledge.

Package required

We need to add the following JSON package in package.json file. This package will help to access the information in ASP.NET Core 1.0.

"Microsoft.Extensions.Configuration.Json": "1.0.0"

Creating a json file

We are creating a configuration JSON file in our application.

Right click -> Add -> New Item.. -> Click “Code” inside the Installed Category -> Select json file.

Configuration Source

Configuration Source

appsettings.json

We have added one sample message inside the JSON file.

{
  "Message": { "WelcomeMessage": "Configure Source In ASP.NET Core 1.0 !!" },
  "Microsoft": {
    "Platform": [ "My", "New", "Article !! " ]
  }
}

JSON configuration

In the following code, we used “AddJsonFile(“json file name”)” extension method. We can access the JSON file in our application through this extension “AddJsonFile(“appsettings.json”)”.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Linq;

namespace ConfiguringSource
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var ConfigBuilder = new ConfigurationBuilder().SetBasePath(env.ContentRootPath)
                                                          .AddJsonFile("appsettings.json");
            Configuration = ConfigBuilder.Build();
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public IConfiguration Configuration { get; set; }
        public void ConfigureServices(IServiceCollection services)
        {

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.Run(async (context) =>
            {
                var Message = Configuration["Message:WelcomeMessage"];
                var Details = Configuration.GetSection("Microsoft:Platform").GetChildren().Select(x => x.Value);//array of value
                await context.Response.WriteAsync(string.Join(" ", Details) + Message);
                
            });
        }
    }
}

IConfiguration Interface

IConfiguration Interface represents a set of key/value application configuration properties.

Possible Error !!

We have added all packages and libraries but we are getting the “File Not Found” Exception. This is not a big deal! We can resolve this Internal Server Error in two ways.

Error

Error

Fixing Error 1 :

We need to specify the exact path of “appsettings.json” file. The following code includes “IHostingEnvironment” to find the path of the JSON file or any other file inside the application.

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json");

    Configuration = builder.Build();
}

Fixing Error 2 :

This is a common answer. We can directly put “Directory.GetCurrentDirectory()” to find the path of the file.

public Startup()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");

Configuration = builder.Build();
}

project.json

The final structure of project.json file in our application is given below.

{
  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.1",
      "type": "platform"
    },
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.Extensions.Configuration.Json": "1.0.0"
  },

  "tools": {
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
  },

  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dotnet5.6",
        "portable-net45+win8"
      ]
    }
  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true
    }
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "web.config"
    ]
  },

  "scripts": {
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

Array

The following code will read the array of value in JSON file.

app.Run(async (context) =>
            {
                var Message = Configuration["Message:WelcomeMessage"];
                var Details = Configuration.GetSection("Microsoft:Platform").GetChildren().Select(x => x.Value);//array of value
                await context.Response.WriteAsync(string.Join(" ", Details) + Message);
                
            });

Output

Output

Output

Reference

Conclusion

We learned about adding a configuration source in ASP.NET Core 1.0 and I hope you liked this article. Please share your valuable suggestions and feedback.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: