ASP.NET Core 项目实战(统一接口返回格式)

1.创建公共返回类


image.png

Api统一返回格式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WebModel.Other
{
    /// 
    /// 统一返回数据格式(模型)
    /// 
    public class ApiResult
    {
        /// 
        /// 返回是否成功
        /// 
        public bool IsSuccess { get; set; }
        /// 
        /// 返回数据源
        /// 
        public object Result { get; set; }
        /// 
        /// 返回消息
        /// 
        public string Msg { get; set; }

    }
}

分页格式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WebModel.Other
{
    /// 
    /// 分页模型
    /// 
    public class PageInfo
    {
        /// 
        /// 总数
        /// 
        public int Total { get; set; }
        /// 
        /// 分页数据
        /// 
        public object Data { get; set; }
    }
}

Token格式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WebModel.Other
{
    /// 
    /// token 模型
    /// 
    public class JwtTokenOptions
    {
        public string Audience { get; set; }

        public string SecurityKey { get; set; }

        public string Issuer { get; set; }

    }
}

2.返回统一格式接口帮助类


image.png
using WebModel.Other;

namespace WebApi.Config
{
    /// 
    /// 返回统一格式接口帮助类
    /// 
    public class ResultHelper
    {
        public static ApiResult Success(object res)
        {
            return new ApiResult()
            {
                IsSuccess=true,
                Result=res,
                Msg = "请求成功"
            };
        }

        public static ApiResult Error(string message)
        {
            return new ApiResult()
            {
                IsSuccess = false,
                Msg = message
            };
        }
    }
}

你可能感兴趣的:(ASP.NET Core 项目实战(统一接口返回格式))