c# – 如何读取.net内核中的连接字符串?

c# – 如何读取.net内核中的连接字符串?,第1张

概述我想从配置文件只读一个连接字符串,因此 将一个名称为“AppAettings.json”的文件添加到我的项目中,并在其上添加此内容: {"ConnectionStrings": { "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet- WebApplica71d622;Trusted_Conne 我想从配置文件只读一个连接字符串,因此
将一个名称为“AppAettings.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;

现在我如何读取c#中的“DefaultConnection”,并将其存储在.net核心中的字符串变量中?

解决方法 您可以使用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; }}

启动:

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"));

然后在家庭控制器中:

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": "[email protected]","Pass": "123456789","Port": "25"  }
总结

以上是内存溢出为你收集整理的c# – 如何读取.net内核中的连接字符串?全部内容,希望文章能够帮你解决c# – 如何读取.net内核中的连接字符串?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1259976.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存