how to configure .net core Web Application database credentials - c#

I have created a simple .net core application connecting to mongoDb as described here https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mongo-app?view=aspnetcore-7.0&tabs=visual-studio
Database connection information is configured in appsettings.json file.
"DataSource": {
"ConnectionString": "mongodb://localhost:27017",
"DatabaseName": "Root",
"CollectionName": "ApiLog"
},
I have a matching class
public class DatabaseSettings
{
public string ConnectionString { get; set; } = null!;
public string DatabaseName { get; set; } = null!;
public string CollectionName { get; set; } = null!;
}
I dont want to store db info in a file so how can I configure connection information in a production environment?
I expect something like
dotnet app.dll -DataSource.ConnectionString = mongodb://localhost:27017
in Program.cs i have;
builder.Services.Configure<DatabaseSettings>(
builder.Configuration.GetSection("DataSource"))
I want to access this configuration whenever i need it via dependency injection
public class LogService
{
private readonly IMongoCollection<ElekseLog> _collection;
public LogService(
IOptions<DatabaseSettings> databaseSettings)
{
var mongoClient = new MongoClient(
databaseSettings.Value.ConnectionString);
var mongoDatabase = mongoClient.GetDatabase(
databaseSettings.Value.DatabaseName);
_collection = mongoDatabase.GetCollection<ElekseLog>(
databaseSettings.Value.CollectionName);
}
}
But I couldn't make it work...

You can use this syntax:
dotnet app.dll --DataSource:ConnectionString=mongodb://localhost:27017
And access the value using:
var connectionString = builder.Configuration["DataSource:ConnectionString"];
Check documentation

Related

How do you implement DI for IConfiguration in ASP.NET Core 6?

I've been following the official Microsoft documentation and I've tried to enchance my codebase like the following:
public class GRequestModel(IConfiguration config) => _config = config;
{
private readonly IConfiguration Configuration;
public string path { get; set; }
public string secret { get; set; }
public string response { get; set; }
public string remoteip { get; set; }
public GRequestModel(string res, string remip)
{
response = res;
remoteip = remip;
var secret = Configuration["GoogleRecaptchaV3:Secret"];
var path = Configuration["GoogleRecaptchaV3:ApiUrl"];
if (String.IsNullOrWhiteSpace(secret) || String.IsNullOrWhiteSpace(path))
{
//Invoke logger
throw new Exception(
"Invalid 'Secret' or 'Path' properties in appsettings.json. " +
"Parent: GoogleRecaptchaV3.");
}
}
}
But I keep getting a lot of errors if I do it like it's written in the documentation...
To clarify - my goal is to read the secret and API URL from appsettings.json and use this to set the values for Google's reCAPTCHA v3.
I need to do this because I want to migrate my web app to a stable version of .NET 6.
Firstly, the syntax you have is wrong. Dependency injection should be done through the constructor (although some IoC containers provide property injection too):
public class GRequestModel
{
public string path { get; set; }
public string secret { get; set; }
public string response { get; set; }
public string remoteip { get; set; }
public GRequestModel(IConfiguration configuration, string res, string remip)
{
response = res;
remoteip = remip;
var secret = configuration["GoogleRecaptchaV3:Secret"];
var path = configuration["GoogleRecaptchaV3:ApiUrl"];
if (String.IsNullOrWhiteSpace(secret) || String.IsNullOrWhiteSpace(path))
{
//Invoke logger
throw new Exception("Invalid 'Secret' or 'Path' properties in appsettings.json. Parent: GoogleRecaptchaV3.");
}
}
}
Now we're accepting IConfiguration in the correct place, we can address how to create this object and get IConfiguration from the container. To do this, I'm going to create a delegate in the same GRequestModel class:
public class GRequestModel
{
public delegate GRequestModel Factory(string res, string remip);
Then we can register this factory with the container:
services.AddTransient<GRequestModel.Factory>(serviceProvider =>
(string res, string remip) => new GRequestModel(serviceProvider.GetRequiredService<IConfiguration>(), res, remip));
Now you can inject GRequestModel.Factory and create a GRequestModel using it:
public class SomeOtherClass
{
public SomeOtherClass(GRequestModel.Factory grequestFactory)
{
GRequestModel grm = grequestFactory("resValue", "remipValue");
}
}
Try it online
Edit: In response to your comment about it being more complicated than the documentation, that's because your use case is more complicated than the documentation examples. Specifically, you want to accept parameters res and remip.
Consider this example:
public class MyService
{
private readonly IConfiguration _configuration;
public MyService(IConfiguration configuration)
{
_configuration = configuration;
}
public void DoSomething(string res, string remip)
{
string configValue = _configuration["myConfigKey"];
}
}
You can register this and use this like so:
services.AddTransient<MyService>();
public class MyOtherClass
{
public MyOtherClass(MyService service)
{
service.DoSomething("resValue", "remipValue");
}
}
This is much simpler because you don't also need to inject the parameters into the constructor. It really depends on what you're trying to do as to which is the best option.

C# bind whole appSettings file to class

In C# we can bind some settings in appSettings to class, for example like that:
var connectionStrings = new ConnectionStrings();
var sectionConnectionString = Configuration.GetSection("ConnectionStrings");
In appsettings it looks like below:
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
And when I want to bind Logging I need to call another bind:
Configuration.GetSection("Logging");
How can I bind whole appsettings file? GetSection with empty string doesn't work:
Configuration.GetSection("");
You need a Class for your config and afterwards you can use this (You do not need to map every setting, just the ones you need):
var configObject = Configuration.Get<ConfigObject>();
Example config object:
public class ConfigObject {
public Logging Logging { get; set; }
public string AllowedHosts { get; set; }
public ConnectionStrings ConnectionStrings { get; set; }
}
public class Logging {
public LogLevel LogLevel { get; set; }
}
public class LogLevel {
public string Default { get; set; }
}
public class ConnectionStrings {
public string ConnString1 { get; set; }
}
Hint:
if you're not using aspnetcore you probably need to also include this NuGet package: Microsoft.Extensions.Configuration.Binder
You can use the Configuration instance as it is.
You can bind the settings to a class:
var appSettings = Configuration.Get<AppSettings>();
Or you can inject the settings with the Options pattern
services.Configure<AppSettings>(Configuration);

ASP.NET Core IOptions - Is it Possible to Populate Config POCO Sensitive Fields From Environment Variables In Production Environment?

I am learning ASP.NET Core 3.1 and have managed to get my webapp set up for development environment so that a Configuration POCO is populated from appsettings.development.json with sensitive fields populated from user secrets. These are AccessKey and SecretKey in the listing below. They are populated using IOptions pattern and CreateDefaultBuilder
Configuration POCO
public class S3Config
{
public const string SectionName = "S3Settings";
public string AccessKey { get; set; }
public string Bucket { get; set; }
public string Endpoint { get; set; }
public string SecretKey { get; set; }
}
appsettings.development.json
{
"S3Settings":
{
"Bucket": "images",
"Endpoint": "localhost:9000"
},
}
Is it possible to populate the sensitive fields in the configuration POCO AccessKey and SecretKey from environment variables when running in production environment? For example:
export S3Settings_AccessKey=accesskeyexample
export S3Settings_SecretKey=secretkey12345
appsettings.json Populates non sensitive fields in POCO
{
"S3Settings":
{
"Bucket": "images",
"Endpoint": "localhost:9000"
},
}

How to validate config values from appSettings.json file automatically during DI setup?

I added configurations to the appSettings.json file in my .NET Core project. For the sake of simplicy I'm taking database settings as an example. So in the settings file you would have
{
"Database": {
"Host": "localhost",
"Port": 1234,
"Database": "myDb",
"Username": "username",
"Password": "pw",
"EnablePooling": true
}
}
When configuring the services in the Startup.cs file I want to make those settings accessible via dependency injection. The data model for this is
public class DatabaseSettings
{
public string Host { get; set; }
public ushort Port { get; set; }
public string Database { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public bool EnablePooling { get; set; }
}
and I configure it this way
private void SetupSettings(IServiceCollection services)
{
ServiceProvider serviceProvider = services.BuildServiceProvider();
IConfiguration configuration = serviceProvider.GetService<IConfiguration>();
IConfigurationSection databaseConfigurationSection = configuration.GetSection("Database");
services.Configure<DatabaseSettings>(databaseConfigurationSection);
}
Lastly I want to validate those settings. I know that I can create a validator class implementing the IValidateOptions interface.
public class DatabaseSettingsValidator : IValidateOptions<DatabaseSettings>
{
private readonly IList<string> failures;
public DatabaseSettingsValidator()
{
failures = new List<string>();
}
public ValidateOptionsResult Validate(string databaseSettingsName, DatabaseSettings databaseSettings)
{
if (databaseSettings == null)
failures.Add($"{databaseSettingsName} are required.");
if (string.IsNullOrEmpty(databaseSettings?.Host))
failures.Add($"{nameof(databaseSettings.Host)} must not be empty.");
if (string.IsNullOrEmpty(databaseSettings?.Database))
failures.Add($"{nameof(databaseSettings.Database)} must not be empty.");
if (failures.Any())
return ValidateOptionsResult.Fail(failures);
return ValidateOptionsResult.Success;
}
}
but do I have to create this class and call the Validate method on my own? Maybe there is something like this sample code?
.
services.ValidateConfiguration<IOptions<DatabaseSettings>, DatabaseSettingsValidator>();
So you pass in the configured settings and the validator to use.
but I'm struggling with two questions:
Is there a way I can collect all failures instead of returning after
one? So you would get a list of failures instead of having to fix one
by one.
Do I have to create this class and call the Validate method on my own?
Maybe there is something like this sample code?
services.ValidateConfiguration<IOptions,
DatabaseSettingsValidator>(); So you pass in the configured settings
and the validator to use.
Yes, we could collect all failures list and display them at once, and we could also create a class which contains the Validate method. Please check the following steps:
First, since the class name is "DatabaseSettings", it better sets the config section name as the same as the class name:
{
"DatabaseSettings": {
"Host": "localhost",
"Port": 1234,
"Database": "myDb",
"Username": "username",
"Password": "pw",
"EnablePooling": true
}
}
[Note] If using a different name, the value might not map to the Database Setting class, so when validate the data, they all null.
Second, using the Data Annotations method adds validation rules to the model properties.
public class DatabaseSettings
{
[Required]
public string Host { get; set; }
[Required]
public ushort Port { get; set; }
[Required]
public string Database { get; set; }
[Required]
public string Username { get; set; }
[Required]
public string Password { get; set; }
[Required]
public bool EnablePooling { get; set; }
}
Third, create a ServiceCollectionExtensions class which contains the ConfigureAndValidate method:
public static class ServiceCollectionExtensions
{
public static IServiceCollection ConfigureAndValidate<T>(this IServiceCollection #this,
IConfiguration config) where T : class
=> #this
.Configure<T>(config.GetSection(typeof(T).Name))
.PostConfigure<T>(settings =>
{
var configErrors = settings.ValidationErrors().ToArray();
if (configErrors.Any())
{
var aggrErrors = string.Join(",", configErrors);
var count = configErrors.Length;
var configType = typeof(T).Name;
throw new ApplicationException(
$"Found {count} configuration error(s) in {configType}: {aggrErrors}");
}
});
}
Then, register the ConfigureAndValidate service:
public void ConfigureServices(IServiceCollection services)
{
services.ConfigureAndValidate<DatabaseSettings>(Configuration);
}
Finally, get the Exception list.
public class HomeController : Controller
{
private readonly DatabaseSettings_settings;
public HomeController(IOptions<DatabaseSettings> settings)
{
_settings = settings.Value; // <-- FAIL HERE THROW EXCEPTION
}
}
Then, test result like this (I removed the Host and Username from the appSettings.json):
More detail information, you can check this blog:Validating configuration in ASP.NET Core
ValidateOptions are mainly for complex scenario, the purpose of using ValidateOptions is that you can move the validate logic out of startup.
I think for your scenario, you can use below code as a reference
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions<MyConfigOptions>()
.Bind(Configuration.GetSection(MyConfigOptions.MyConfig))
.ValidateDataAnnotations()
.Validate(config =>
{
if (config.Key2 != 0)
{
return config.Key3 > config.Key2;
}
return true;
}, "Key3 must be > than Key2."); // Failure message.
services.AddControllersWithViews();
}
For more details, please refer to this document
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-3.1#options-validation

Correct way to initialize settings in .net core 2.2?

I created an REST api application which has many settings and stored in database. These settings are used during filtering and inserting data to the table.
Because I need to access settings every time I need to insert data. Instead of accessing settings from database, I created a global settings class and I put every settings in that class.
public static class GlobalSettings
{
public static string Setting_1;
public static string Setting_2;
public static string Setting_3;
public static string Setting_4;
public static void Initialize(ISettingsRepo repo)
{
try
{
var settings = new GSettings(repo);
Setting_1 = settings.SetSetting_1();
Setting_2 = settings.SetSetting_2();
Setting_3 = settings.SetSetting_3();
Setting_4 = settings.SetSetting_4();
}
catch (Exception ex)
{
throw new Exception("Error when loading settings.\r\n" + ex.Message);
}
}
}
Here ISettingsRepo is scoped service that will load the settings from database. The functions will initialize the settings to the properties.
Now to initialize GlobalSettings I used configure method in startup class like this.
using (var scope = app.ApplicationServices.CreateScope())
{
Settings.GlobalSettings.Initialize(scope.ServiceProvider
.GetRequiredService<Data_Repo.Settings.ISettingsRepo>());
}
Now I can use this in controller or anywhere in my api and get settings without accessing database. Also I can reload the GlobalSettings any time if settings are updated. But does this method correct way or has memory leak problems?
Is there any better method to do this.?
Example
My appsetting.json have structure like this.
"EmailSettings": {
"MailServer": "",
"MailPort": ,
"Email": "",
"Password": "",
"SenderName": "",
"Sender": "",
"SysAdminEmail": ""
},
I will define my class like this
public class EmailSettings
{
public string MailServer { get; set; }
public int MailPort { get; set; }
public string SenderName { get; set; }
public string Sender { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string SysAdminEmail { get; set; }
}
So we have the the config structure. The last thing we need is register inside Startup.cs
services.Configure<EmailSettings>(configuration.GetSection("EmailSettings"));
To use it inside service class
private readonly IOptions<EmailSettings> _emailSetting;
public EmailSender(IOptions<EmailSettings> emailSetting)
{
_emailSetting = emailSetting;
}
email.From.Add(new MailboxAddress(_emailSetting.Value.SenderName, _emailSetting.Value.Sender));

Categories