C# - Get Connectionstring from Appsettings.Json of a dotnet Core MVC application from a Data Access Library

Asked

Viewed 2,633 times

0

I have an application in . Net Core MVC and I do the data access part using a Dll. How to configure a Connection String according to what was configured in my appSettings.Json of the Netcore MVC application?

    private static string _ConnectionString;

    private static string ConnectionString
    {
        get { return _ConnectionString; }

        set
        {
            _ConnectionString = 
                "Data Source=SERVIDOR;Persist Security Info=True;User ID=ID; Password=Password; Initial Catalog=BASE";
        }
    }
  • Making _Connectionstring public and assigning value to startup?

1 answer

2

Hello, using a webapi aspnet core Voce can do as follows. See if for Voce this solves, or can adapt to your problem

In the controller you create a builder that receives a IConfiguration and assign to a private variable, later you can use it by invoking it as follows configuration["ConnectionString"] see for example

appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionString": "Host= localhost; user= user; pass=pass"
}

The Controller

public class ValuesController : ControllerBase
{
    private IConfiguration configuration;
    public ValuesController(IConfiguration config){
        configuration = config;
    }

    // GET api/values
    [HttpGet]
    public ActionResult<string> Get()
    {
        return Ok(configuration["ConnectionString"]);
    }

}
  • Hello, you can use connectionString with : Configuration.Getconnectionstring("name of the variable in appSettings")

Browser other questions tagged

You are not signed in. Login or sign up in order to post.