public class Student
{
public int Id { get;set;}
public string Name { get;set;}
public int Age { get;set;}
public string Email { get;set;}}
1.
2.
3.
4.
5.
6.
7.
接下来,让我们创建一个StudentsController类来处理HTTP请求:
[Route("api/students")]
public class StudentsController : Controller
{
private static List<Student> students = new List<Student>{
new Student { Id =1, Name ="John Smith", Age =20, Email ="john.smith@example.com"},
new Student { Id =2, Name ="Jane Doe", Age =19, Email ="jane.doe@example.com"},
new Student { Id =3, Name ="Bob Johnson", Age =21, Email ="bob.johnson@example.com"}};[HttpGet]
public IActionResult GetAllStudents(){
return Ok(students);}[HttpGet("{id}")]
public IActionResult GetStudent(int id){
var student = students.FirstOrDefault(s => s.Id== id);
if (student ==null){
return NotFound();}
return Ok(student);}[HttpPost]
public IActionResult CreateStudent([FromBody] Student student){
student.Id= students.Max(s => s.Id)+1;
students.Add(student);
return CreatedAtAction(nameof(GetStudent), new { id = student.Id}, student);}[HttpPut("{id}")]
public IActionResult UpdateStudent(int id,[FromBody] Student student){
var existingStudent = students.FirstOrDefault(s => s.Id== id);
if (existingStudent ==null){
return NotFound();}
existingStudent.Name= student.Name;
existingStudent.Age= student.Age;
existingStudent.Email= student.Email;
return NoContent();}[HttpDelete("{id}")]
public IActionResult DeleteStudent(int id){
var student = students.FirstOrDefault(s => s.Id== id);
if (student ==null){
return NotFound();}
students.Remove(student);
return NoContent();}
最后,我们使用HTTP状态代码200 OK、201 Created、204 No Content和404 Not Found来指示每个操作的结果。
四、向Student类添加更多属性
以下是Student类的更新版本,其中包含一些附加的属性:
public class Student
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public string Email { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
}
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
在该类的更新版本中,我们添加了以下属性:
FirstName:学生的名字。
LastName:学生的姓。
Address:学生的街道地址。
City:学生居住的城市。
State:学生所在的州。
ZipCode:学生地址的邮政编码。
这些附加的属性可以提供有关学生的更多信息,并可用于API中的筛选、排序和搜索操作。
五、将另一个属性添加到Student类
关于学生所学的科目
以下是Student类的更新版本,其中包含学生所学科目的附加属性:
public class Student
{
public int Id { get;set;}
public string FirstName { get;set;}
public string LastName { get;set;}
public int Age { get;set;}
public string Email { get;set;}
public string Address { get;set;}
public string City { get;set;}
public string State { get;set;}
public string ZipCode { get;set;}
public List<string> SubjectsTaken { get;set;}}
var student = new Student
{
Id =1,
FirstName ="John",
LastName ="Doe",
Age =20,
Email ="john.doe@example.com",
Address ="123 Main St",
City ="Anytown",
State ="CA",
ZipCode ="12345",
SubjectsTaken = new List<string>{"Math","Science","History"}};
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
而且,您可以像这样检索给定学生的科目列表:
var student = GetStudent(1);
var subjects = student.SubjectsTaken;
public class Subject
{
public int Id { get;set;}
public string Name { get;set;}
public string Teacher { get;set;}
public int Credits { get;set;}}
public class Student
{
public int Id { get;set;}
public string FirstName { get;set;}
public string LastName { get;set;}
public int Age { get;set;}
public string Email { get;set;}
public string Address { get;set;}
public string City { get;set;}
public string State { get;set;}
public string ZipCode { get;set;}
public List<Subject> SubjectsTaken { get;set;}}
var student = new Student
{
Id =1,
FirstName ="John",
LastName ="Doe",
Age =20,
Email ="john.doe@example.com",
Address ="123 Main St",
City ="Anytown",
State ="CA",
ZipCode ="12345",
SubjectsTaken = new List<Subject>{
new Subject { Id =1, Name ="Math", Teacher ="Mr. Smith", Credits =4},
new Subject { Id =2, Name ="Science", Teacher ="Ms. Jones", Credits =3}}};
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
您可以检索给定学生的科目列表,如下所示:
var student = GetStudent(1);
var subjects = student.SubjectsTaken;
1.
2.
七、将Student类中的State属性更改为枚举类型
public enum State
{
AL, AK, AZ, AR, CA, CO, CT, DE, FL, GA, HI, ID, IL,IN, IA, KS, KY, LA, ME,
MD, MA, MI, MN, MS, MO, MT, NE, NV, NH, NJ, NM, NY, NC, ND, OH, OK,OR, PA,
RI, SC, SD, TN, TX, UT, VT, VA, WA, WV, WI, WY
}
public class Student
{
public int Id { get;set;}
public string FirstName { get;set;}
public string LastName { get;set;}
public int Age { get;set;}
public string Email { get;set;}
public string Address { get;set;}
public string City { get;set;}
public State State { get;set;}
public string ZipCode { get;set;}
public List<Subject> SubjectsTaken { get;set;}}
var student = new Student
{
Id =1,
FirstName ="John",
LastName ="Doe",
Age =20,
Email ="john.doe@example.com",
Address ="123 Main St",
City ="Anytown",
State = State.CA,
ZipCode ="12345",
SubjectsTaken = new List<Subject>{
new Subject { Id =1, Name ="Math", Teacher ="Mr. Smith", Credits =4},
new Subject { Id =2, Name ="Science", Teacher ="Ms. Jones", Credits =3}}};
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
您可以像这样检索给定学生的State属性:
var student = GetStudent(1);
var state = student.State;
1.
2.
八、为必填项ID、FirstName和EmailID添加校验器
以下是Student类的更新版本,其中包括Id、FirstName和Email属性的验证:
public class Student
{
private int _id;
private string _firstName;
private string _email;
public int Id
{
get { return _id;}set{
if (value <=0){
throw new ArgumentException("Id must be greater than zero.");}
_id = value;}}
public string FirstName
{
get { return _firstName;}set{
if (string.IsNullOrEmpty(value)){
throw new ArgumentException("First name cannot be null or empty.");}
_firstName = value;}}
public string LastName { get;set;}
public int Age { get;set;}
public string Email
{
get { return _email;}set{
if (string.IsNullOrEmpty(value)){
throw new ArgumentException("Email cannot be null or empty.");}
_email = value;}}
public string Address { get;set;}
public string City { get;set;}
public State State { get;set;}
public string ZipCode { get;set;}
public List<Subject> SubjectsTaken { get;set;}}
var student = new Student
{
Id =1,
FirstName ="John",
LastName ="Doe",
Age =20,
Email ="john.doe@example.com",
Address ="123 Main St",
City ="Anytown",
State = State.CA,
ZipCode ="12345",
SubjectsTaken = new List<Subject>{
new Subject { Id =1, Name ="Math", Teacher ="Mr. Smith", Credits =4},
new Subject { Id =2, Name ="Science", Teacher ="Ms. Jones", Credits =3}}};
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
如果尝试使用无效数据创建新的学生对象,将引发ArgumentException异常:
var invalidStudent = new Student
{
Id =0,// throws ArgumentException
FirstName ="",// throws ArgumentException
LastName ="Doe",
Age =20,
Email ="",// throws ArgumentException
Address ="123 Main St",
City ="Anytown",
State = State.CA,
ZipCode ="12345",
SubjectsTaken = new List<Subject>()};
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
九、使StudentsController控制器异步
这里是StudentsController类的更新版本,它使用异步方法:
[ApiController][Route("api/[controller]")]
public class StudentsController : ControllerBase
{
private readonly IStudentRepository _studentRepository;
public StudentsController(IStudentRepository studentRepository){
_studentRepository = studentRepository;}[HttpGet]
public async Task<ActionResult<IEnumerable<Student>>> GetAllStudents(){
var students = await _studentRepository.GetAllStudentsAsync();
return Ok(students);}[HttpGet("{id}")]
public async Task<ActionResult<Student>> GetStudentById(int id){
var student = await _studentRepository.GetStudentByIdAsync(id);
if (student ==null){
return NotFound();}
return Ok(student);}[HttpPost]
public async Task<ActionResult<Student>> CreateStudent(Student student){
if (!ModelState.IsValid){
return BadRequest(ModelState);}
await _studentRepository.AddStudentAsync(student);
return CreatedAtAction(nameof(GetStudentById), new { id = student.Id}, student);}[HttpPut("{id}")]
public async Task<IActionResult> UpdateStudent(int id, Student student){
if (id != student.Id){
return BadRequest();}
if (!ModelState.IsValid){
return BadRequest(ModelState);}
var existingStudent = await _studentRepository.GetStudentByIdAsync(id);
if (existingStudent ==null){
return NotFound();}
await _studentRepository.UpdateStudentAsync(student);
return NoContent();}[HttpDelete("{id}")]
public async Task<IActionResult> DeleteStudent(int id){
var existingStudent = await _studentRepository.GetStudentByIdAsync(id);
if (existingStudent ==null){
return NotFound();}
await _studentRepository.DeleteStudentAsync(existingStudent);
return NoContent();}}