其他分享
首页 > 其他分享> > NetCore 封装JsonResult通用返回模型

NetCore 封装JsonResult通用返回模型

作者:互联网

1.NuGet添加引用,包名: Microsoft.AspNetCore.Mvc

1.1.步骤为:选中类库 / 右键 / 管理NuGet程序包 / 包名 / 安装

1.2.或者如下图

 2.Demo如下

using Microsoft.AspNetCore.Mvc;
using CustAotuBuilderFramework.Extends;
using Xunit.Abstractions;
using Xunit;

namespace CoreXUnitTestProject.TestCache
{
    public class TestJsonResult : BaseTesting
    {
        public TestJsonResult(ITestOutputHelper testOutputHelper) : base(testOutputHelper)
        {
        }

        [Fact]
        public void Run()
        {
            var data = 1024;
            {
                var jsonResult = Helper<int>.Success(data);
                _testOutputHelper.WriteLine($"jsonResult:{jsonResult.ToJson()}");
            }
            {
                var jsonResult = Helper<int>.Builder(data, 500, "Error");
                _testOutputHelper.WriteLine($"jsonResult:{jsonResult.ToJson()}");
            }
        }
    }

    /// <summary>
    /// 帮助类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class Helper<T>
    {
        public static JsonResult Success(T body)
        {
            var rspData = RspData<T>.Success(body, 200, string.Empty);
            return new JsonResult(rspData);
        }
        public static JsonResult Builder(T body, int status, string message)
        {
            var rspData = RspData<T>.Success(body, status, message);
            return new JsonResult(rspData);
        }
    }

    /// <summary>
    /// 返回通用模型
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class RspData<T>
    {
        public T Body { get; set; }

        public int Status { get; set; }

        public string Message { get; set; }

        public RspData() { }

        public RspData(T body, int status, string message)
        {
            Body = body;
            Status = status;
            Message = message;
        }

        public static RspData<T> Success(T body, int status, string message) => new RspData<T>(body, status, message);
    }
}

 

标签:body,status,JsonResult,封装,NetCore,jsonResult,RspData,message,public
来源: https://www.cnblogs.com/CRobot/p/15503417.html