1/27/17

ASPNET Core MVC display database connection string to page

ASPNET Core MVC display database connection string on page

I was recently asked how to display the database connection string for an ASPNET Core MVC application. This is not as straight forward as it was with previous version of ASPNET when you could just use the ConfigurationManager to read settings from the applications web.config file.

In ASPNET Core MVC there is no web.config, usually custom settings will be created in a appsettings.json file. To get access to the appsettings file, first there are some configuration settings that will need to be changed.
First this is how the current connection string is defined in the appsettings.json
Connection String
"database": {
"connection": "Data Source=.;Initial Catalog=OdeToFood;Integrated  Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
}
Create a class to store the connection string property (AppSettings.cs)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace CoreTest
{
    public class AppSettings
    {
        public string connection { get; set; }
    }
}
Update the project Startup.cs file
Ensure the constructor is reading the appsettings.json file
public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();
    }
Add these lines to ConfigureServices
 services.AddOptions();
 services.Configure<AppSettings>(Configuration.GetSection("database"));
Update the controller (HomeController.cs)
Create the app settings variable and inject the AppSettings into the constructor
 public class HomeController : Controller
 {
    private AppSettings _AppSettings;

    public HomeController(IOptions<AppSettings> settings)
    {
        _AppSettings = settings.Value;
 }
Add the controller method that will send the connection string to the view
 public async Task ContentAction()
    {
        var constr = _AppSettings.connection;
        var jsonString = "{\"connectionString\""+ constr + "}";
        byte[] data = Encoding.UTF8.GetBytes(jsonString);
        Response.ContentType = "application/json";
        await Response.Body.WriteAsync(data, 0, data.Length);
    }
Call the controller method from the View (Index.cshtml)
 <div>
    <a asp-controller="Home" asp-action="ContentAction" class="btn btn-  success confirmCreate">
        Generate Response
        <i class="fa fa-angle-left"></i>
    </a>
</div>
View Output will display the connection string
{"connectionString"Data Source=.;Initial Catalog=OdeToFood;Integrated     Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False}

No comments:

Post a Comment