1.在新建的空项目上新建json文件,如下图:
2.在json文件里面添加数据:
例如:
{
"ClassNo": "1",
"ClassDesc": "ASP.NET.Core 101",
"Students": [
{
"name": "zhangsan",
"age": "13"
},
{
"name": "lisi",
"age": "22"
},
{
"name": "wangwu",
"age": "25"
}
]
}
2.保存并修改文件属性:
3.新建appsettings.json文件数据访问的类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DemoNew
{
public class Class
{
public int ClassNo { get; set; }
public string ClassDesc { get; set; }
public List<Student> Students { get; set; }
}
public class Student
{
public string Name { get; set; }
public string Age { get; set; }
}
}
4.将类添加到服务(server)里面,用于访问:
5.调用数据:
由于appsettings.json是系统默认的文件,就不需要通过路径将文件数据加载进来,可以在类里面直接访问数据,下面是采用一个视图去访问的代码:
@using Microsoft.Extensions.Options;
@inject IOptionsSnapshot<DemoNew.Class> myclass
@{
ViewData["Title"] = "Index";
}
<h2>Index</h2>
<h3>Class No: @myclass.Value.ClassNo</h3>
<h3>Class V: @myclass.Value.ClassDesc</h3>
<h4>
@foreach (var student in myclass.Value.Students)
{
<span>StudentName: @student.Name</span>
<span>StudentAge: @student.Age</span>
}
</h4>foreach
对应的控制器:
运行查看结果: