.Net Core: Set Connection String with Windows Authentication in AppSettings.json

In a Connection String with Windows Authentication, the Integrated Security property is set to TRUE.

SQL Server Connection String for Windows Authentication is defined as follows and it consists of the following properties.
Data Source – The name of the SQL Server and its Instance.
Initial Catalog – The name of the Database.
Integrated Security - By default False. If set true it signifies that Windows Authentication needs to be used.
{
 "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Connection=True;MultipleActiveResultSets=true",
    "MyConn": "Data Source=.\\SQL2017;Initial Catalog=AjaxSamples;Integrated Security=true"
 }
}
 
Reading Connection String from AppSettings.json file using IConfiguration interface
In the below example, the IConfiguration is injected in the Controller and assigned to the private property Configuration.
Then inside the Controller, the Connection String is read from the AppSettings.json file using the GetConnectionString function.
public class HomeController : Controller
{
    private IConfiguration Configuration;
 
    public HomeController(IConfiguration _configuration)
    {
        Configuration = _configuration;
    }
    public IActionResult Index()
    {
        string connString = this.Configuration.GetConnectionString("MyConn");
        return View();
    }
}

Post a Comment

0 Comments