简介

上一篇我们说了如何实现一个WebApi,并运行起来

这次我们来说说WebApi的内在,我们到底做了哪些事情

仓库地址:https://github.com/NeuCharFramework/NCF

欢迎收藏,欢迎Star哦

NCF WebApi中 Controller的全解析-LMLPHP

步骤

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项目(此项目默认加载即可)

NCF WebApi中 Controller的全解析-LMLPHP

 双击Senparc.Web进入文件编辑

引入项目

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

2.在WorkShop.Xncf.WebApiDemo01 项目下建立Controllers目录,如图所示

NCF WebApi中 Controller的全解析-LMLPHP

3.在Controller下面建立BaseController用来统一处理返回的内容方法

NCF WebApi中 Controller的全解析-LMLPHP

 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来处理统一返回的数据格式

NCF WebApi中 Controller的全解析-LMLPHP

 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,并创建具体的使用方法

NCF WebApi中 Controller的全解析-LMLPHP

 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调用的方法

NCF WebApi中 Controller的全解析-LMLPHP

 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

NCF WebApi中 Controller的全解析-LMLPHP

 NCF WebApi中 Controller的全解析-LMLPHP

 NCF WebApi中 Controller的全解析-LMLPHP

有疑问随时欢迎交流

06-13 20:13