Core 2.0中如何在ConfigurationBuilder中SetBasePath [英] How to SetBasePath in ConfigurationBuilder in Core 2.0

查看:58
本文介绍了Core 2.0中如何在ConfigurationBuilder中SetBasePath的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Core 2.0 的 ConfigurationBuilder 中设置基本路径.

How can I set the base path in ConfigurationBuilder in Core 2.0.

我用谷歌搜索并找到了这个问题、this 来自 Microsoft 文档,以及 2.0 在线文档,但他们似乎正在使用 1.0.0-beta8.

I have googled and found this question, this from Microsoft docs, and the 2.0 docs online but they seem to be using a version of Microsoft.Extension.Configuration from 1.0.0-beta8.

我想阅读appsettings.json.在 Core 2.0 中有没有新的方法来做到这一点?

I want to read appsettings.json. Is there a new way of doing this in Core 2.0?

using System;
using System.IO;
using Microsoft.Extensions.Configuration;
namespace ConsoleApp2
{
    class Program
    {
        public static IConfigurationRoot Configuration { get; set; }

        static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory()) // <== compile failing here
                .AddJsonFile("appsettings.json");

            Configuration = builder.Build();

            Console.WriteLine(Configuration.GetConnectionString("con"));
            Console.WriteLine("Press a key...");
            Console.ReadKey();
        }
    }
}

appsetting.json

{
  "ConnectionStrings": {
    "con": "connection string"
  }
}

更新:除了添加 Microsoft.Extensions.Configuration.FileExtensions 如下所示通过 Set 我还需要添加 Microsoft.Extensions.Configuration.Json 以获取 AddJsonFile 扩展.

UPDATE: In addition to adding Microsoft.Extensions.Configuration.FileExtensions as indicated below by Set I also needed to add Microsoft.Extensions.Configuration.Json to get the AddJsonFile extension.

推荐答案

SetBasePath 扩展方法定义在 Config.FileExtensions.

您需要添加对 Microsoft.Extensions.Configuration.FileExtensions 的引用 包.

解决AddJsonFile,添加对Microsoft.Extensions的引用.Configuration.Json 包.

这篇关于Core 2.0中如何在ConfigurationBuilder中SetBasePath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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