为了规范数据返回格式,现在将结果约定为返回以下三个字段:
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. 测试结果


    定义数据接口返回数据格式_字段

    定义数据接口返回数据格式_接口测试_02

    定义数据接口返回数据格式_其他_03