NCF WebApi中 Controller的全解析

MartyZane發表於2021-06-13

簡介

上一篇我們說了如何實現一個WebApi,並執行起來

這次我們來說說WebApi的內在,我們到底做了哪些事情

倉庫地址:https://github.com/NeuCharFramework/NCF

歡迎收藏,歡迎Star哦

 

 

 

步驟

1.在Senparc.Web中引用Senparc.Xncf.Swagger專案(此專案預設載入即可)

2.在WorkShop.Xncf.WebApiDemo01 專案下建立Controller目錄

3.在Controller下面建立BaseController用來統一處理返回的內容方法

4.在Models下面建立BaseResult來處理統一返回的資料格式

5.新建ColorController,並建立具體的使用方法

6.在ColorService裡面增加Api呼叫的方法

7.執行測試結果

 

實施

1.在Senparc.Web中引用Senparc.Xncf.Swagger專案(此專案預設載入即可)

 

 雙擊Senparc.Web進入檔案編輯

引入專案

1 <ProjectReference Include="..\Senparc.Xncf.Swagger\Senparc.Xncf.Swagger.csproj" />

2.在WorkShop.Xncf.WebApiDemo01 專案下建立Controllers目錄,如圖所示

3.在Controller下面建立BaseController用來統一處理返回的內容方法

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Threading.Tasks;
 5 using Microsoft.AspNetCore.Mvc;
 6 using WorkShop.Xncf.WebApiDemo01.Models.DatabaseModel.VO;
 7 using WorkShop.Xncf.WebApiDemo01.Services;
 8 using Senparc.Ncf.Core.Cache;
 9 
10 namespace WorkShop.Xncf.WebApiDemo01.Controllers
11 {
12     public class BaseController : ControllerBase
13     {
14 
15         public IActionResult Success(object data)
16         {
17             var response = new BaseResult<object>(200, "請求成功", data);
18             return Ok(response);
19         }
20 
21         public IActionResult Fail(object data)
22         {
23             var response = new BaseResult<object>(201, "請求失敗", data);
24             return Ok(response);
25         }
26     }
27 }

4.在Models下面建立BaseResult來處理統一返回的資料格式

 1 using Senparc.CO2NET.Helpers;
 2 using System;
 3 using System.Collections.Generic;
 4 using System.Text;
 5 
 6 namespace WorkShop.Xncf.WebApiDemo01.Models.DatabaseModel.VO
 7 {
 8     public class BaseResult<T>
 9     {
10         public BaseResult(int code,string msg,T data)
11         {
12             Code = code;
13             Msg = msg;
14             Data = data;
15             RequestTime = $"{ string.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now)}";
16         }
17 
18         /// <summary>
19         /// 錯誤碼,200 表示成功
20         /// </summary>
21         public int Code { get; set; } = 0;
22 
23         /// <summary>
24         /// 訊息
25         /// </summary>
26         public string Msg { get; set; }
27 
28         /// <summary>
29         /// 主體資料
30         /// </summary>
31         public T Data { get; set; }
32 
33         /// <summary>
34         /// 請求時間
35         /// </summary>
36         public string RequestTime { get; set; }
37 
38 
39     }
40 }

5.新建ColorController,並建立具體的使用方法

 1 using Microsoft.AspNetCore.Hosting;
 2 using Microsoft.AspNetCore.Http;
 3 using Microsoft.AspNetCore.Mvc;
 4 using Microsoft.AspNetCore.Mvc.ModelBinding;
 5 using Microsoft.Extensions.Options;
 6 using System;
 7 using System.Collections.Generic;
 8 using System.IO;
 9 using System.Linq;
10 using System.Text;
11 using System.Text.RegularExpressions;
12 using System.Threading.Tasks;
13 using Senparc.Ncf.Core.Cache;
14 using Senparc.CO2NET.Cache;
15 using Senparc.CO2NET.Cache.CsRedis;
16 using WorkShop.Xncf.WebApiDemo01.Models.DatabaseModel.VO;
17 using WorkShop.Xncf.WebApiDemo01.Models.DatabaseModel.Config;
18 using WorkShop.Xncf.WebApiDemo01.Utils;
19 using WorkShop.Xncf.WebApiDemo01.Services;
20 using WorkShop.Xncf.WebApiDemo01.Models.DatabaseModel.Dto;
21 
22 namespace WorkShop.Xncf.WebApiDemo01.Controllers
23 {
24     /// <summary>
25     /// 檔案上傳介面
26     /// </summary>
27     [Route("api/v{version:apiVersion}/[controller]/[action]")]
28     [ApiController]
29     [ApiVersion("1")]
30     public class ColorController : BaseController
31     {
32         private readonly ColorService colorService;
33 
34         public ColorController(ColorService colorService)
35         {
36             this.colorService = colorService;
37         }
38 
39         /// <summary>
40         /// 獲取當前顏色
41         /// </summary>
42         /// <returns></returns>
43         [HttpGet]
44         public async Task<IActionResult> GetColorAsync()
45         {
46             try
47             {
48                 var response = await colorService.ApiGetColorAsync();
49                 return Success(response);
50             }
51             catch (Exception ex)
52             {
53                 return Fail(ex.Message);
54             }
55         }
56 
57         /// <summary>
58         /// 設定顏色
59         /// </summary>
60         /// <param name="type">型別(1-變亮;2-變暗;3-隨機;)</param>
61         /// <returns></returns>
62         [HttpPost]
63         public async Task<IActionResult> SetColorAsync(int type)
64         {
65             try
66             {
67                 var response = await colorService.ApiSetColorAsync(type);
68                 return Success(response);
69             }
70             catch (Exception ex)
71             {
72                 return Fail(ex.Message);
73             }
74         }
75     }
76 }

6.在ColorService裡面增加Api呼叫的方法

 1 using Senparc.Ncf.Core.Enums;
 2 using Senparc.Ncf.Repository;
 3 using Senparc.Ncf.Service;
 4 using WorkShop.Xncf.WebApiDemo01.Models.DatabaseModel.Dto;
 5 using System;
 6 using System.Threading.Tasks;
 7 
 8 namespace WorkShop.Xncf.WebApiDemo01.Services
 9 {
10     public class ColorService : ServiceBase<Color>
11     {
12         public ColorService(IRepositoryBase<Color> repo, IServiceProvider serviceProvider)
13             : base(repo, serviceProvider)
14         {
15         }
16 
17         public async Task<ColorDto> CreateNewColor()
18         {
19             Color color = new Color(-1, -1, -1);
20             await base.SaveObjectAsync(color).ConfigureAwait(false);
21             ColorDto colorDto = base.Mapper.Map<ColorDto>(color);
22             return colorDto;
23         }
24 
25         public async Task<ColorDto> Brighten()
26         {
27             //TODO:非同步方法需要新增排序功能
28             var obj = this.GetObject(z => true, z => z.Id, OrderingType.Descending);
29             obj.Brighten();
30             await base.SaveObjectAsync(obj).ConfigureAwait(false);
31             return base.Mapper.Map<ColorDto>(obj);
32         }
33 
34         public async Task<ColorDto> Darken()
35         {
36             //TODO:非同步方法需要新增排序功能
37             var obj = this.GetObject(z => true, z => z.Id, OrderingType.Descending);
38             obj.Darken();
39             await base.SaveObjectAsync(obj).ConfigureAwait(false);
40             return base.Mapper.Map<ColorDto>(obj);
41         }
42 
43         public async Task<ColorDto> Random()
44         {
45             //TODO:非同步方法需要新增排序功能
46             var obj = this.GetObject(z => true, z => z.Id, OrderingType.Descending);
47             obj.Random();
48             await base.SaveObjectAsync(obj).ConfigureAwait(false);
49             return base.Mapper.Map<ColorDto>(obj);
50         }
51 
52         //TODO: 更多業務方法可以寫到這裡
53 
54 
55         #region 介面要請求的方法
56         public async Task<ColorDto> ApiSetColorAsync(int type)
57         {
58             ColorDto dto;
59             switch (type)
60             {
61                 case 1:
62                     {
63                         dto = await Brighten();
64                         break;
65                     }
66                 case 2:
67                     {
68                         dto = await Darken();
69                         break;
70                     }
71                 default:
72                     {
73                         dto = await Random();
74                         break;
75                     }
76             }
77             return dto;
78         }
79 
80         public async Task<object> ApiGetColorAsync()
81         {
82             var obj = this.GetObject(z => true, z => z.Id, OrderingType.Descending);
83             return obj;
84         }
85         #endregion
86 
87     }
88 }

7.執行測試結果

https://localhost:44311/senparc-api-docs/index.html

 

 

 

 

 

 

有疑問隨時歡迎交流

相關文章