I have a separate class library project(.NET Framework 4.8) to access the DB. This class library is written in Visual Basic(VB).
Recently, due to a new requirement, I had to add a web API layer into my solution to expose the data through endpoints.
I created a new .NET Core 2.1 Web API project in my existing solution. I configured the app settings in appSettings.json in .NET Core instead of App.config in .NET Framework as per the specifications.
Now the below code fails (I am not able to access my configuration settings).
Public connectionString As String = System.Configuration.ConfigurationManager.AppSettings("ConnectionString")
Error: system.typeinitializationexception
Note: This code was previously working. Not able to access the configuration settings.
Alternative tried: I tried to create a .NET Framework Web API (v4.8) instead of .NET Core Web API, and it worked. So, please provide me a solution to access the appSettings.json from .NET Core Web API project to .NET Framework Class Library (v4.8) which is written in VB.
How to access appSettings.json which belongs to a .NET Core Web API project from a .NET Framework Class Library project in the same solution
As we know, ASP.NET Core use different configuration settings. To achieve your above requirement, you can try following approaches:
Approach 1: modify your Class Library method(s) to accept additional parameter, then you can read ConnectionString
etc from Web.config or appsettings.json and pass it as parameter while you call method within corresponding Apps.
Approach 2: modify and extend your Class Library to make it works with ASP.NET Core configuration settings, like below.
Imports System.Configuration
Imports Microsoft.Extensions.Configuration
Public Class DbGeneric
Private ReadOnly _configuration As IConfiguration
Public Sub New(ByVal configuration As IConfiguration)
_configuration = configuration
End Sub
Public Sub New()
End Sub
Public Function GetAll() As String
Dim connectionString As String = ConfigurationManager.ConnectionStrings("DefaultConnection").ConnectionString
Return connectionString
End Function
Public Function GetAllForCore() As String
Dim connectionString As String = _configuration("ConnectionStrings:DefaultConnection").ToString()
Return connectionString
End Function
End Class
In ASP.NET app
var dbGeneric = new MyClassLibraryVB.DbGeneric();
var con_str = dbGeneric.GetAll();
In ASP.NET Core app
public class ValuesController : ControllerBase
{
private readonly IConfiguration Configuration;
public ValuesController(IConfiguration configuration)
{
Configuration = configuration;
}
public IActionResult GetAll()
{
var dbGeneric = new MyClassLibraryVB.DbGeneric(Configuration);
var con_str = dbGeneric.GetAllForCore();
ConnectionStrings in appsettings.json
"ConnectionStrings": {
"DefaultConnection": "{conection_string_for_netcore}"
}
Test Result