简体   繁体   English

如何从 asp.net 内核中的外部 Json 文件访问数据?

[英]How Can I Access Data From External Json File in asp.net core?

I want to access data from a json file in my file directory.我想从我的文件目录中的 json 文件访问数据。

I have tried using StreamReader but it does not deserialize the data.我曾尝试使用StreamReader ,但它不会反序列化数据。

string json = r.ReadToEnd();

WorkFlowConfiguration items = 
    JsonConvert.DeserializeObject<WorkFlowConfiguration>(json);

Debug.WriteLine(items.WorkFlowAction);
Console.WriteLine(items.WorkFlowAction);

items.WorkFlowAction.ForEach(el => Console.WriteLine(el.ToString()));

There are two ways to get the external json file like below:有两种方法可以获取外部 json 文件,如下所示:

1.Model: 1.Model:

public class Test
{
    public string status { get; set; }
    public int code { get; set; }
    public string message { get; set; }
}

2.Json file: 2.Json文件:

  {
    "status": "succeess",
    "code": 1,
    "message": "login succeeded!"
  }

3.The first way(Use StreamReader ): 3.第一种方式(使用StreamReader ):

using (StreamReader r = new StreamReader("C:\\test.json"))
    {
         string json = r.ReadToEnd();
         Test item =JsonConvert.DeserializeObject<Test>(json);
    }

4.The second way(Use File.ReadAllText ): 4.第二种方式(使用File.ReadAllText ):

var jsonString = System.IO.File.ReadAllText("C:\\test.json");
Test items =JsonConvert.DeserializeObject<Test>(jsonString);

if you want to access from startup class如果你想从启动 class 访问

"MySettings": {  
    "DbConnection": "abc",  
    "Email": "abc@domain.com",  
    "SMTPPort": "5605"  
  }  


public Startup(IConfiguration configuration)
{   
     var dbConnection= configuration["MySettings:DbConnection"];
}

or if you want in your controller, you must inject IConfiguration in you constructor或者如果你想在你的 controller 中,你必须在你的构造函数中注入 IConfiguration

public UserController(IConfiguration configuration)  
{  
   configuration = configuration["MySettings:DbConnection"]; 
}  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM