While there are a myriad of threads on here about this subject, the ones I looked at did not address my exact need.
ASP.NET Core 3.1 Web app:
I have a C# method that looks like this:
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace ClientsUI.Data
{
public class ClientsService
{
private readonly ClientsDbContext _context;
private readonly IConfiguration _iconfiguration;
public ClientsService(ClientsDbContext context, IConfiguration iconfiguration)
{
_context = context;
_iconfiguration = iconfiguration;
}
public async Task<List<BillingCodes>>
GetBillingCodesNameTestAsync()
{
return await _context.BillingCodes.Where(c => c.Name.Contains("Test") && c.ClientId.ToString() != "ABC123")
.AsNoTracking()
.ToListAsync();
}
}
}
And an appsettings.json that looks like this:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"ConnectionStrings": {
"DefaultConnection": "myconnectionstring"
},
"SqlFilters": {
"NameFilter": "Test",
"ClientIdFilter": "ABC123"
}
}
In the GetBillingCodesNameTestAsync method, I need to replace “Test” and “ABC123” with a call to the appsettings.json file, something along the lines of Configuration.GetSqlFilters... which I can’t get to work properly, hence my post.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
I would use the strongly typed interface available in IConfiguration.
class SqlFilters {
string NameFilter { get; set; }
string ClientIdFilter { get; set; }
}
and then use
var sqlFilters = _iconfiguration.GetSection("SqlFilters").Get<SqlFilters>();
Accessing your variables is then as easy as accessing properties on a class (that is sqlFilters.NameFilter and sqlFilters.ClientIdFilter respectively).
Method 2
return await _context.BillingCodes.Where(c => c.Name.Contains(_iconfiguration["SqlFilters:NameFilter"]) && c.ClientId.ToString() != _iconfiguration["SqlFilters:ClientIdFilter"])
.AsNoTracking()
.ToListAsync();
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0