如何从json文件中读取值

时间:2017-10-04 07:59:32

标签: asp.net .net json .net-core

我有一个.net核心应用程序,用于发送电子邮件,用于发送电子邮件的电子邮件和密码存储在json文件中。我在开发时能够正常发送电子邮件,但是当我发布时,应用程序无法从json文件中读取电子邮件和密码。代码中是否有错误?

public class Startup
{
    public static IConfiguration Configuration { get; set; }

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

        Configuration = builder.Build();
    }

     public void ReadFromJson()
    {
            var email = ($"{Configuration["option1"]}");
            var password = ($"{Configuration["option2"]}");
            var path = ($"{Configuration["option3"]}");
            File.WriteAllText("/var/hey.txt",email);
   }

Json文件(appsettings.json):

   {
    "option1": "something@outlook.com",
    "option2": "something",
   }

3 个答案:

答案 0 :(得分:1)

使用IConfiguration读取配置数据

IConfiguration _iconfiguration;  
public ConstructorForClass(IConfiguration iconfiguration) {  
  _iconfiguration = iconfiguration;  
}

public void ReadFromJson()
    {
var email =_iconfiguration["option1"];  
var email =_iconfiguration["option1"];  
   }

将此放入您的启动方法

services.Configure<ClassName>(Configuration); 

你把ReadFromJson放在启动时,不是一个好的做法,创建新类来读取数据,并从那里访问你想要的地方

答案 1 :(得分:0)

为什么在这里使用字符串互操作?你试过吗

var option1 = Configuration.GetValue<string>("option1");

答案 2 :(得分:0)

protected void Button1_Click(object sender, EventArgs e)
    {
        jsonstring = client.DownloadString("http://maps.googleapis.com/maps/api/geocode/json?address=Kokuvil");
        dynamic dynObj = JsonConvert.DeserializeObject(jsonstring);

        Response.Write(dynObj.results[0].address_components[1].long_name);
    }