您的位置:首页 > Web前端 > JavaScript

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

2017-02-10 13:21 260 查看
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进行处理
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  json