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进行处理