Как читать строку подключения in.NET ядро?


Я хочу прочитать только строку подключения из файла конфигурации и для этого добавить файл с именем "appsettings.json " в мой проект и добавить этот контент на нем:

{
"ConnectionStrings": {
  "DefaultConnection": "Server=(localdb)mssqllocaldb;Database=aspnet-

 WebApplica71d622;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
    "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
    "Default": "Debug",
    "System": "Information",
    "Microsoft": "Information"
   }
 }
}

ВКЛ ASP.NET я использовал это:

 var temp=ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

теперь как я могу прочитать "DefaultConnection" в C# и сохранить его в строковой переменной в .NET Core?

5 51

5 ответов:

вы можете сделать это с расширением GetConnectionString-метод:

string conString = Microsoft
   .Extensions
   .Configuration
   .ConfigurationExtensions
   .GetConnectionString(this.Configuration, "DefaultConnection");

System.Console.WriteLine(conString);

или со структурированным классом для DI:

public class SmtpConfig
{
    public string Server { get; set; }
    public string User { get; set; }
    public string Pass { get; set; }
    public int Port { get; set; }
}

Startup:

public IConfigurationRoot Configuration { get; }


// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    // http://developer.telerik.com/featured/new-configuration-model-asp-net-core/
    // services.Configure<SmtpConfig>(Configuration.GetSection("Smtp"));
    Microsoft.Extensions.DependencyInjection.OptionsConfigurationServiceCollectionExtensions.Configure<SmtpConfig>(services, Configuration.GetSection("Smtp"));

а потом в home-controller:

public class HomeController : Controller
{

    public SmtpConfig SmtpConfig { get; }
    public HomeController(Microsoft.Extensions.Options.IOptions<SmtpConfig> smtpConfig)
    {
        SmtpConfig = smtpConfig.Value;
    } //Action Controller


    public IActionResult Index()
    {
        System.Console.WriteLine(SmtpConfig);
        return View();
    }

С этим в appsettings.json:

"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\mssqllocaldb;Database=aspnet-WebApplica71d622;Trusted_Connection=True;MultipleActiveResultSets=true"
},

"Smtp": {
    "Server": "0.0.0.1",
    "User": "user@company.com",
    "Pass": "123456789",
    "Port": "25"
  }

опубликованный ответ в порядке, но напрямую не ответил на тот же вопрос, который у меня был о чтении в строке подключения. Путем долгих поисков я нашел более простой способ сделать это.

В Автозагрузку.cs

public void ConfigureServices(IServiceCollection services)
{
    ...
    // Add the whole configuration object here.
    services.AddSingleton<IConfiguration>(Configuration);
}

в вашем контроллере добавьте поле для конфигурации и параметр для него на конструкторе

private readonly IConfiguration configuration;

public HomeController(IConfiguration config) 
{
    configuration = config;
}

Теперь позже в вашем коде просмотра вы можете получить к нему доступ, например:

connectionString = configuration.GetConnectionString("DefaultConnection");

способ, который я нашел для решения этой проблемы, заключался в использовании AddJsonFile в построителе при запуске (что позволяет ему найти конфигурацию, хранящуюся в appsettings.json file), а затем использовать его для установки частной переменной _config

public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        _config = builder.Build();
    }

и тогда я мог бы установить строку конфигурации следующим образом:

var connectionString = _config.GetConnectionString("DbContextSettings:ConnectionString"); 

это на dotnet core 1.1

см. ссылку для получения дополнительной информации: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-strings

JSON

    {
      "ConnectionStrings": {
        "BloggingDatabase": "Server=(localdb)\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;"
      },
    }

Запуск C#.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<BloggingContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("BloggingDatabase")));
}

вы можете использовать метод расширения конфигурации: getConnectionString ("DefaultConnection")

https://docs.asp.net/projects/api/en/latest/autoapi/Microsoft/Extensions/Configuration/ConfigurationExtensions/index.html#Microsoft.Extensions.Configuration.ConfigurationExtensions.GetConnectionString