.NET Core 返回结果统一封装

本文使用.NET Core Webapi演示!

 

一:新建.NetCore webapi项目

 

为了方便开发,简化代码,也为了与前端方便对接,需要对接口服务返回结果进行统一处理。

 

二:定义返回结果结构

我们需要定义一个统一返回结果泛型类ApiResult

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class ApiResult<T>
{
    /// <summary>
    /// 错误代码
    /// </summary>
    public ApiResultCode Code { get; set; }
    /// <summary>
    /// 错误信息
    /// </summary>
    public string Message { get; set; }
    /// <summary>
    /// 具体数据
    /// </summary>
    public T Data { get; set; }
}

  三:封装ControllerBase以及通用路由

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
  [Route("api/[controller]")]
    [ApiController]
    public class CommonController : ControllerBase
    {
        protected ApiResult<T> GenActionResultGenericEx<T>(T datas, ApiResultCode code = ApiResultCode.Success, string message = "", Exception ex = null)
        {
            if (ex != null)
            {
                code = ApiResultCode.Failed;
                message = string.IsNullOrWhiteSpace(message) ? ex.Message : $"{message}\n{ex.Message}";
#if Debug
                message = string.IsNullOrWhiteSpace(message) ? ex.Message : $"{message}\n{ex.Message}";
#endif
            }
            else if (datas == null)
 
            {
                code = ApiResultCode.Empty;
                message = "数据为空";
            }
            var result = new ApiResult<T>
            {
                Code = code,
                Message = message,
                Data = datas
            };
            return result;
        }
    }

  

通用数据格式只封装了三种Code:

1
public enum ApiResultCode{     <br>   //失败         Failed, <br>       //成功        Success,      <br>  //数据为空        Empty,    }

  

可以根据实际业务添加

 

四:在Controller层使用

 

五:查看返回数据

 

 

eg:当然还有很多方法实现.NET Core 返回结果统一封装,我这里只写了其中一种!

 

最后我希望所有neter关注前沿技术,不要故步自封。

最后大家如果喜欢我的文章,还麻烦给个关注, 希望net生态圈越来越好!

个人公众号【黑哥聊dotNet】

b站【黑哥聊编程】

posted @   黑哥聊dotNet  阅读(545)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示