定义数据接口返回数据格式

本文介绍了如何定义和实现数据接口的返回格式,包括Code、Msg和Data三个字段。通过创建result类并进行接口测试来确保其正确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

为了规范数据返回格式,现在将结果约定为返回以下三个字段:
Code,Msg,Data

  1. 定义result类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MyBlogNew.Common
{
    public class Result<T>
    {
        public int Code {get;set; }

        public string Msg { get; set; }

        public T Data { get; set; }
    }
}
  1. 编写接口测试:
  public Result<int> GetDiariesTotalNumOne()
        {
            Result<int> result = new Result<int>();
            try
            {
                using (var entity = new MyBlogNewEntities())
                {
                    int totalPage = entity.Diaries.ToList().Count();
                    result.Code = 1;
                    result.Msg = "success";
                    result.Data = totalPage;
                    return result;
                }
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }

        public Result<List<string>> GetDiariesTotalNumTwo()
        {
            Result<List<string>> result = new Result<List<string>>();
            try
            {
                using (var entity = new MyBlogNewEntities())
                {
                    int totalPage = entity.Diaries.ToList().Count();
                    result.Code = 1;
                    result.Msg = "success";
                    result.Data = new List<string> {"hello","world" } ;
                    return result;
                }
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
public Result<Dictionary<int,string>> GetDiariesTotalNumTwo()
        {
            Result<Dictionary<int, string>> result = new Result<Dictionary<int, string>>();
            try
            {
                using (var entity = new MyBlogNewEntities())
                {
                    int totalPage = entity.Diaries.ToList().Count();
                    result.Code = 1;
                    result.Msg = "success";
                    
                    Dictionary<int,string> map = new Dictionary<int, string>();
                    map.Add(1,"hello");
                    map.Add(2,"world");
                    result.Data = map;
                    return result;
                }
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
  1. 测试结果


    2789632-19f51878a7741b8a.png

    2789632-d33d733b9dee75be.png

    2789632-a087410b933c4ba7.png
2789632-3b18269684ea9294.png
公众号.png
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值