C# 创建 RESTful 服务(Web API)

1. 创建项目

  • VSCode 打开准备用来存放项目文件夹的文件夹;
  • VSCode 中打开终端,运行命令:dotnet new webapi -o HelloRestful
  • 当对话框询问是否要将所需资产添加到项目时,选择“是”。

2. 添加自定义逻辑

  • 在解决方案中(Controllers 同级)新建一个 Models 文件夹;
  • 在 Models 目录下新建 EmployeeInfo.cs 类,代码如下:
    C# 创建 RESTful 服务(Web API)
    using System;
    
    namespace HelloRestful.Controllers
    {
        public class EmployeeInfo
        {
            public int EmployeeNo { get; set; }
            public string EmployeeName { get; set; }
            public int Age { get; set; }
            public int Sex { get; set; }
            public string Position { get; set; }
            public bool IsActive { get; set; } = false;
            public DateTime CreateDate { get; set; } = DateTime.Now;
        }
    }
    View Code
  • 在 Controllers 目录下新建 EmployeeInfoController.cs 类,代码如下:
    C# 创建 RESTful 服务(Web API)
    using System.Collections.Generic;
    using Microsoft.AspNetCore.Mvc;
    
    namespace HelloRestful.Controllers
    {
        [Route("api/[controller]")]
        [ApiController]
        public class EmployeeInfoController
        {
            private List<EmployeeInfo> employeeInfos = new List<EmployeeInfo>
            {
                new EmployeeInfo{
                    EmployeeNo = 1,
                    EmployeeName = "Jack",
                    Age = 21,
                    Sex = 1,
                    Position = "Front-end Development",
                },
                new EmployeeInfo{
                    EmployeeNo = 2,
                    EmployeeName = "Tom",
                    Age = 23,
                    Sex = 0,
                    Position = "Front-end Development",
                },
                new EmployeeInfo{
                    EmployeeNo = 3,
                    EmployeeName = "Martin",
                    Age = 22,
                    Sex = 1,
                    Position = ".Net Development",
                },
            };
    
            [HttpGet]
            public IEnumerable<EmployeeInfo> Get()
            {
                return employeeInfos;
            }
        }
    }
    View Code

 

3. 允许跨域配置

 

 

 

 

 

 

 

 

 

 

 

 

上一篇:13.5 实现博客的增删改


下一篇:26个大小写字母对应的哈希值