asp.net核心库项目中的连接字符串 [英] connection string in asp.net core library project

查看:82
本文介绍了asp.net核心库项目中的连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有asp.net核心库项目.我想在其中添加连接字符串.我没有启动课程.我需要在哪里放置连接字符串以及如何获取它?

I have asp.net core library project. I want to add connection string in it. I don't have startup class in this. Where I need to place connection string and how to fetch it?

请提出建议.

推荐答案

在dotnet核心中,您可以使用json文件管理配置,而json文件是配置应用程序的许多方式之一.

In dotnet core you can manage configuration using json files, which is one in many ways to configure your application.

根据 dotnet核心配置文档,您可以简单地做(从链接参考中复制)

According to the dotnet core configuration documentation you can simply do (copied from link reference)

using Microsoft.Extensions.Configuration;
using System;
using System.IO;

// Add NuGet <package id="Microsoft.Extensions.Configuration" and
// <package id="Microsoft.Extensions.Configuration.Json"
// .NET Framework 4.x use the following path:
//.SetBasePath(Path.Combine(Directory.GetCurrentDirectory(), @"..\.."))

public class Program
{
    static public IConfigurationRoot Configuration { get; set; }
    public static void Main(string[] args = null)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json");

        Configuration = builder.Build();

        Console.WriteLine($"option1 = {Configuration["option1"]}");
        Console.WriteLine($"option2 = {Configuration["option2"]}");
        Console.WriteLine(
            $"option1 = {Configuration["subsection:suboption1"]}");
    }
}

然后在您的appsettings.json文件中可以添加:

Then in your appsettings.json file you can add:

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

并使用Configuration.GetConnectionString("BloggingDatabase")

我也建议您阅读有关连接的 dotnet核心文档字符串

I can recommend also reading the dotnet core documentation regarding connection strings

正如评论员在您的帖子中提到的那样,请勿将连接字符串和配置文件添加到您的库代码中-可以从控制台应用程序或Web应用程序执行此操作!

As the commentors mention on your post, don't add connection strings and config files to your library code - do this from your console application or the web application!

dotnet核心的其他配置形式包括用户机密环境变量,也许还有XML文件或其他评论中指出的存储方式

Additional forms of configuration for dotnet core includes user secrets, environment variables and perhaps XML files or other forms of storage, as pointed out in the comments

这篇关于asp.net核心库项目中的连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆