Hi @William Buchanan ,
In the Class Library, you can install the Microsoft.Extensions.Configuration
and Microsoft.Extensions.Configuration.Json
package via NuGet.
Then refer to the following code to add the appSettings.json file
and read the configuration.
public interface IDataRepository
{
string GetConnection();
}
public class DataRepository : IDataRepository
{
private readonly IConfiguration _config;
public DataRepository(IConfiguration configuration)
{
_config= configuration;
}
public string GetConnection()
{
string c = Directory.GetCurrentDirectory();
IConfigurationRoot configuration = new ConfigurationBuilder().SetBasePath(c).AddJsonFile("appSettings.json").Build();
string connectionStringIs = configuration.GetConnectionString("WebApplication1Context");
return connectionStringIs;
}
}
In the API application, add the Class Library reference, and register the above repository.
builder.Services.AddScoped<IDataRepository, DataRepository>();
In the appSetting.json file, add the connection string like this:
"ConnectionStrings": {
"WebApplication1Context": "Server=(localdb)\\mssqllocaldb;Database=WebApplication1;Trusted_Connection=True;MultipleActiveResultSets=true"
},
Then, in the API controller, call the Class Library method:
[ApiController]
public class UsersController : ControllerBase
{
private readonly IDataRepository _repo;
public UsersController(IDataRepository dataRepository)
{
_repo = dataRepository;
}
[HttpGet]
[Route("getconnectionstring")]
public IActionResult GetCurrentUserGroups()
{
var connection = _repo.GetConnection();
return Ok(connection);
}
}
The result as below:
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion