如何在Controller 中获取JSON文件的内容

来源:互联网 发布:surge for mac 破解 编辑:程序博客网 时间:2024/05/22 12:41

Step1. 获取JSON文件路径

1.在Controller文件中添加引用

using Microsoft.AspNetCore.Hosting;

2.为Controller类添加私有成员

private IHostingEnvironment hostingEnvironment;

3.在构造函数中为成员赋值

public [Controller](IHostingEnvironment env){    this.hostingEnvironment = env;}

4.假设JSON文件位于wwwroot目录下,则其路径通过这样获取:

string jsonFilePath = $@"{hostingEnvironment.WebRootPath}\[filename].json"))

Step2. 获取JSON文件内容

private string GetJSONFileContent(string jsonFilePath){    FileStream stream = new FileStream(jsonFilePath, FileMode.Open);    StreamReader reader = new StreamReader(stream);    StringBuilder builder = new StringBuilder();    string input = null;    while ((input = reader.ReadLine()) != null)    {        builder.Append(input);    }    return builder.ToString();}

Step3. 解析JSON对象
参见:如何将JSON对象传递给Controller进行处理

0 0
原创粉丝点击