1. 程式人生 > 實用技巧 >C# 建立 RESTful 服務(Web API)

C# 建立 RESTful 服務(Web API)

1. 建立專案

  • VSCode 開啟準備用來存放專案資料夾的資料夾;
  • VSCode 中開啟終端,執行命令:dotnet new webapi -o HelloRestful
  • 當對話方塊詢問是否要將所需資產新增到專案時,選擇“是”。

2. 新增自定義邏輯

  • 在解決方案中(Controllers 同級)新建一個 Models 資料夾;
  • 在 Models 目錄下新建 EmployeeInfo.cs 類,程式碼如下:
    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 類,程式碼如下:
    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. 允許跨域配置