Asp.Net Core 全局请求返回封装

为什么要封装全局请求返回

  1. 专注于业务
  2. 更好的在Swagger上展示接口返回内容

开源项目地址

地址

代码

ApiResult.cs

using Lotus.Blog.TNT.Ext;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Lotus.Blog.TNT.Web
{
    public class ApiResult
    {
        /// <summary>
        /// 是否为成功请求
        /// </summary>
        public bool Success
        { get; set; }

        /// <summary>
        /// 状态码
        /// </summary>
        public string Code
        { get; set; }

        /// <summary>
        /// 返回消息
        /// </summary>
        public string Message
        { get; set; }
        
        public DateTime DateTime { get; set; }
        
    }

    public class ApiResult<T> : ApiResult
    {
        public T Data { get; set; }
        
        public static ApiResult<T> SuccessInstance(T data)
        {
            return new ApiResult<T>() { Success = true, Code = "", Message = "", Data = data };

        }

        public static ApiResult<T> FailInstance(string message, string code = "500")
        {
            return new ApiResult<T>() { Success = false, Code = code, Message = message, Data = default(T) };

        }

        public static ApiResult<T> ParamsError(params string[] ps)
        {
            return new ApiResult<T>() { Success = false, Code = "param-error", Message = "参数错误:" + ps.Join(","), Data = default(T) };
        }

        public static ApiResult<T> DataNotExist()
        {
            return new ApiResult<T>() { Success = false, Code = "not-exist", Message = "数据不存在", Data = default(T) };
        }
    }

}

BaseActionFilter.cs

using System;
using Lotus.Blog.TNT.Ext;
using Lotus.Blog.TNT.Web;
using Microsoft.AspNetCore.Mvc;
namespace Lotus.Blog.TNT.Attributes
{
    public abstract class BaseActionFilter:System.Attribute
    {
        
        /// <summary>
        /// 返回JSON
        /// </summary>
        /// <param name="json">json字符串</param>
        /// <returns></returns>
        public ContentResult JsonContent(string json)
        {
            return new ContentResult { Content = json, StatusCode = 200, ContentType = "application/json; charset=utf-8" };
        }
        
        /// <summary>
        /// 返回成功
        /// </summary>
        /// <returns></returns>
        public ContentResult Success()
        {
            ApiResult res = new ApiResult
            {
                Success = true,
                Code = "",
                Message = "请求成功!",
                DateTime = DateTime.Now,
            };

            return JsonContent(res.ToJson());
        }
        
        /// <summary>
        /// 返回成功
        /// </summary>
        /// <param name="data">返回的数据</param>
        /// <returns></returns>
        public ContentResult Success<T>(T data)
        {
            ApiResult<T> res = new ApiResult<T>
            {
                Success = true,
                Message = "请求成功!",
                Code = "",
                DateTime = DateTime.Now,
                Data = data
            };

            return JsonContent(res.ToJson());
        }
        /// <summary>
        /// 返回错误
        /// </summary>
        /// <returns></returns>
        public ContentResult Error()
        {
            ApiResult res = new ApiResult
            {
                Success = false,
                Message = "错误请求!",
                Code = "error",
                DateTime = DateTime.Now,
            };

            return JsonContent(res.ToJson());
        }
        public ContentResult Error(string msg)
        {
            ApiResult res = new ApiResult
            {
                Success = false,
                Message = msg,
                Code = "error",
                DateTime = DateTime.Now,
            };


            return JsonContent(res.ToJson());
        }
        /// <summary>
        /// 返回错误
        /// </summary>
        /// <param name="msg">错误提示</param>
        /// <param name="errorCode">错误代码</param>
        /// <returns></returns>
        public ContentResult Error(string msg, string errorCode)
        {
            ApiResult res = new ApiResult
            {
                Success = false,
                Message = msg,
                Code = errorCode,
                DateTime = DateTime.Now,
            };

            return JsonContent(res.ToJson());
        }
        
    }
}

FormatResponseAttribute.cs

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Lotus.Blog.TNT.Attributes
{
    /// <summary>
    /// 全局返回封装
    /// </summary>
    public class FormatResponseAttribute : BaseActionFilter, IActionFilter
    {
        public void OnActionExecuting(ActionExecutingContext context)
        {
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
            if (context.Result is EmptyResult)
                context.Result = Success();
            else if (context.Result is ObjectResult res)
            {
                context.Result = Success(res.Value);
            }
        }
    }
}

如何使用
在Controller层Controller上增加属性
image.png
实现的效果
image.png
image.png
请求输出

{
"success":true,
"message":"",
"code":"",
"datetime":"2022-01-10 00:06:12",
"data":null
}

这样我们在编写接口的时候不用每次都return Success(data);了可以直接
return data;

# Core  Asp.Net 

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×