Issues with SQL Alias in ConnectionString in appsettings.json

后端 未结 1 470
生来不讨喜
生来不讨喜 2020-12-16 14:06

In my appsettings.json, when I use this snippet:

\"ConnectionStrings\": {
    \"CssDatabase\": \"Server=BLUEJAY\\\\MSSQLSERVER2014;Database=CSS;Trusted_Conne         


        
相关标签:
1条回答
  • 2020-12-16 14:38

    Since information about SQL Aliases stored in Windows registry the Microsoft team decided to drop its support in .NET Core, because it is not cross-platform solution. Here the link to discussion about it.

    However there is workaround(also from this discussion), which worked fine for me, but bear in mind it is still Windows only solution:

    var builder = new SqlConnectionStringBuilder(config.ConnectionString);
    
    var key = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE") == "x86"
        ? @"HKEY_LOCAL_MACHINE\SOFTWARE\ Microsoft\MSSQLServer\Client\ConnectTo"
        : @"HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\MSSQLServer\Client\ConnectTo";
    
    var newSource = (string)Microsoft.Win32.Registry.GetValue(key, builder.DataSource, null);
    if (newSource != null)
        builder.DataSource = newSource.Substring(newSource.IndexOf(',') + 1);
    
    config.ConnectionString = builder.ConnectionString;
    

    If you not storing ConnectionString in the distinct C# class you can just pass the builder.ConnectionString to services in ConfigureServices method like I did below:

    services.AddDbContext<AppDbContext>(
                    opt => opt.UseSqlServer(builder.ConnectionString));
    
    0 讨论(0)
提交回复
热议问题