Home > Back-end >  How can I access my secret key in any class with .NET 6?
How can I access my secret key in any class with .NET 6?

Time:09-21

I have a secret key in a secrets.json file that I would like to access to hide my ConnectionString in my Db Context class. I see a bunch of tutorials with previous versions of .NET but I am confused on how to get this to work so that I don't have to type in the actual string. Can anyone help me? I have already created the secrets.json file and have placed the values inside the file by setting it. I just need help with accessing that value in my context class.

Program.cs:

using ItunesMVC;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

//Not sure if I am doing this right. Should this be here in my Program.cs? 
var itunesDBConnectionString = builder.Configuration["ConnectionStrings:itunesAppDB"];

var secretConfig = builder.Configuration.GetSection("ConnectionStrings").Get<Configuration>();
var secretVar = secretConfig.connectionString;

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

SearchCountContext.cs:

using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;

namespace ItunesMVC
{
    public partial class ItunesSearchDBEntities : DbContext
    {
    
        //Not sure how I can access the secret key in this file.
        private readonly IConfiguration _configuration;
        
        public string ConnectionString { get; private set; }
        
        public ItunesSearchDBEntities(DbContextOptions<ItunesSearchDBEntities> options)
            : base(options)
        {
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.
                optionsBuilder.UseMySql("This is where I have my ConnectionString", Microsoft.EntityFrameworkCore.ServerVersion.Parse("8.0.28-mysql"));
            }
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.UseCollation("utf8mb4_0900_ai_ci")
                .HasCharSet("utf8mb4");

            OnModelCreatingPartial(modelBuilder);
        }

        partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
        
        public DbSet<SearchCount> SearchCounts { get; set; }
    }
}

Configuration.cs:

namespace ItunesMVC;

//Do I need to make this class to access my secret key?
public class Configuration
{
    public string connectionString { get; set; }
}

appsettings.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

CodePudding user response:

after installing Pomelo.EntityFrameworkCore.MySql package

in program.cs file

builder.Services.AddControllersWithViews();


builder.Services.AddDbContextPool<ItunesSearchDBEntities>(options =>
{
    var connetionString = builder.Configuration.GetConnectionString("itunesAppDB");
    options.UseMySql(connetionString, ServerVersion.AutoDetect(connetionString));
});

and remove OnConfiguring method from ItunesSearchDBEntities class

  • Related