给写ajax接口一个通用测试顶目

使用技术:mvc,jquery,json2,反射.

先上效果图

关键代码

View Code
1   //下面三行代码为核心代码,
2                 //使用反射,输入类路经得到类的类型
3                 Type type = Type.GetType(inputClassName);
4                 //得到输入类的实例,并赋值
5                 object t = CommentAjaxInterfaceText.comment.CommentClass.Deserialize(type, inputString);
6                 //使用反射,动态调用所需要的接口,并把输入值对象传递给方法
7                 return this.GetType().GetMethod(interfaceName).Invoke(this, new object[] { t }) as ActionResult;

 

 

配置文件   /config/methodsStructure.txt  的内容

login###
登陆消息###
true###
InLogin###
{"email":"aaaaa@gmail.com","password":"fdsafdsafdsa"}###
{"nickname":"tom","userid":"xxx","sessioncode":"xxxxx","header":"xxxxxx"}#$#

以###为分割符,以#$#为结果符,所代表的意思如下

第一个:接口名称 ,如:login.

第二个:接口描述,如登陆消息.

第三个:表示此接口是否启用,布尔类型(true,false)

第三个:接口输入值,MVC可以自动配置输入的键值对,所以我们以类形式做为输入参数

第四个:接口输出值的参考.

通用测试实现代码

View Code
  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Web;
  5 using System.Web.Mvc;
  6 using CommentAjaxInterfaceText.comment;
  7 using CommentAjaxInterfaceText.ModelInput;
  8 
  9 namespace CommentAjaxInterfaceText.Controllers
 10 {
 11     public class InterfaceController : Controller
 12     {
 13 
 14         #region 测试界面
 15         /// <summary>
 16         /// 用来存放模板里接口基本信息,如果有新的接口添加,只需要在  /config/methodsStructure.txt  添加接口的基本信息,就可以进行接口测试了.
 17         /// </summary>
 18         private static List<InputTemple> config = new List<InputTemple>();
 19 
 20         /// <summary>
 21         /// 提取配置文件信息,并显现在界面上,如方法名列表,
 22         /// </summary>
 23         /// <returns></returns>
 24         [HttpGet]
 25         public ActionResult Test()
 26         {
 27             //读取配置文件
 28             string strconfig = CommentAjaxInterfaceText.comment.CommentClass.ReadFile("/config/methodsStructure.txt");
 29             string[] str = strconfig.Split(new string[] { "#$#", "###" }, StringSplitOptions.RemoveEmptyEntries);
 30             config = new List<InputTemple>();
 31             for (int i = 0; i < str.Length / 6; i++)
 32             {
 33                 InputTemple inputTemple = new InputTemple();
 34                 inputTemple.methods = str[0 + 6 * i].Trim('\r').Trim('\n');
 35                 inputTemple.description = str[1 + 6 * i].Trim('\r').Trim('\n');
 36                 inputTemple.enabled = Convert.ToBoolean(str[2 + 6 * i].Trim('\r').Trim('\n'));
 37                 inputTemple.inputClass = str[3 + 6 * i].Trim('\r').Trim('\n');
 38                 inputTemple.input = str[4 + 6 * i].Trim('\r').Trim('\n');
 39                 inputTemple.output = str[5 + 6 * i].Trim('\r').Trim('\n');
 40                 config.Add(inputTemple);
 41             }
 42             return View(config);
 43         }
 44 
 45         /// <summary>
 46         /// 
 47         /// </summary>
 48         /// <param name="interfaceName">接口名</param>
 49         /// <param name="inputClass">输入参数类型</param>
 50         /// <param name="inputString">输入值,JSON形式</param>
 51         /// <returns></returns>
 52         [HttpPost]        
 53         public ActionResult TestMomber(string interfaceName, string inputClass, string inputString)
 54         {
 55             try
 56             {
 57                 if (String.IsNullOrEmpty(interfaceName))
 58                     return Json("函数名不能为空", JsonRequestBehavior.AllowGet);
 59                 if (String.IsNullOrEmpty(inputString))
 60                     return Json("输入值不能为空", JsonRequestBehavior.AllowGet);
 61                 string inputClassName = "CommentAjaxInterfaceText.ModelInput." + inputClass;   
 62                 //下面三行代码为核心代码,
 63                 //使用反射,输入类路经得到类的类型
 64                 Type type = Type.GetType(inputClassName);
 65                 //得到输入类的实例,并赋值
 66                 object t = CommentAjaxInterfaceText.comment.CommentClass.Deserialize(type, inputString);
 67                 //使用反射,动态调用所需要的接口,并把输入值对象传递给方法
 68                 return this.GetType().GetMethod(interfaceName).Invoke(this, new object[] { t }) as ActionResult;
 69             }
 70             catch (Exception ex)
 71             {
 72                 return Json(ex.Message, JsonRequestBehavior.AllowGet);
 73             }
 74         }
 75 
 76         [HttpPost]
 77         public ActionResult GetFunData(string methods)
 78         {
 79             InputTemple temple = config.Find(P => P.methods == methods);
 80             return Json(temple, JsonRequestBehavior.AllowGet);
 81         }
 82 
 83         #endregion
 84 
 85         #region    一个登录测试接口
 86         /// <summary>
 87         /// 
 88         /// </summary>
 89         /// <param name="intput">输入参数,以类形式传入到接口</param>
 90         /// <returns></returns>
 91         public ActionResult login(InLogin intput)
 92         {
 93             try
 94             {
 95                 OutLogin output = new OutLogin();
 96                 output.header = "XXXX";
 97                 output.nickname = "XX";
 98                 output.sessioncode = "0000";
 99                 output.userid = 25;
100                 return Json(output, JsonRequestBehavior.AllowGet);
101                 
102             }
103             catch (Exception ex)
104             {
105                 return Content(ex.Message);
106             }
107 
108         }
109 
110         #endregion
111 
112     } 
113 }

通用方法

View Code
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.IO;
 6 using System.Text;
 7 
 8 namespace CommentAjaxInterfaceText.comment
 9 {
10     public class CommentClass
11     {
12         #region 读取文件内容
13         /// <summary>
14         /// 读取文件内容
15         /// </summary>
16         /// <param name="file">格式:a/b.htm,相对根目录</param>
17         /// <returns></returns>
18         public static string ReadFile(string file)
19         {
20             try
21             {
22                 System.IO.StreamReader sr = new System.IO.StreamReader(System.Web.HttpContext.Current.Server.MapPath(file), System.Text.Encoding.GetEncoding("GB2312"));// System.Text.Encoding.UTF8
23                 string str = sr.ReadToEnd();
24                 sr.Close();
25                 return str;
26             }
27             catch (Exception ex)
28             {
29                 throw ex;
30             }
31         }
32         #endregion
33 
34         /// <summary>
35         /// json传转成对象
36         /// </summary>
37         /// <param name="type"></param>
38         /// <param name="json"></param>
39         /// <returns></returns>
40         public static object Deserialize(Type type, string json)
41         {
42             using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
43             {
44                 System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(type);
45                 return serializer.ReadObject(ms);
46             }
47         }
48     }
49 }

界面

View Code
  1 @model List<CommentAjaxInterfaceText.comment.InputTemple>
  2 <html>
  3 <head>
  4     <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
  5     <title>接口测试界面</title>
  6     <style type="text/css">
  7         /* reset */
  8         *, body
  9         {
 10             margin: 0;
 11             padding: 0;
 12         }
 13         /* commons */
 14         body
 15         {
 16             font-size: 13px;
 17         }
 18         .clearfix
 19         {
 20             zoom: 1;
 21         }
 22         .clearfix:after
 23         {
 24             content: ´.´;
 25             display: block;
 26             visibility: none;
 27             height: 0;
 28             clear: both;
 29         }
 30         #bd
 31         {
 32             min-height: 50px;
 33             _height: 50px;
 34         }
 35         #bd .right
 36         {
 37             float: right;
 38             width: 100%;
 39             margin-left: -25em;
 40         }
 41         #bd .right .content
 42         {
 43             margin-left: 270px;
 44         }
 45         #bd .left
 46         {
 47             width: 260px;
 48             float: left;
 49         }
 50         p
 51         {
 52             border-width: 1px;
 53             border-style: solid;
 54         }
 55     </style>
 56     <script src="http://www.cnblogs.com/Scripts/jquery.1.7.2.min.js" type="text/javascript"></script>
 57     <script src="http://www.cnblogs.com/Scripts/json2.js" type="text/javascript"></script>
 58     <script type="text/javascript">
 59         $(document).ready(function () {
 60             $(".left p").each(function (i) {
 61                 $(this).bind("click", function (obj) {
 62                     var methods = $(this).find("span:eq(1)").text()
 63                     var desc = "   描述:" + $(this).find("span:eq(0)").text()
 64                     $("#key").val(methods);
 65                     $("#dest").text(desc);
 66                     $("#key").attr("inputClass", $(this).attr("inputClass"));
 67                     $("#input").val("");
 68                     $("#output").val("");
 69                     $("#result").val("");
 70                     var address = window.location.href.replace("test", methods);
 71                     //address = window.location.href.replace("Test", methods);
 72                     $("#address").val(address);
 73                     GetFunData(methods);
 74                 });
 75             });
 76         });
 77 
 78 
 79 
 80         //提交测试
 81         function submitTest() {
 82             var interfaceName = $("#key").val();
 83             var input = $("#input").val();
 84             var inputClass = $("#key").attr("inputClass"); 
 85             $.ajax({
 86                 type: "POST",
 87                 async: false,
 88                 url: "/Interface/TestMomber",
 89                 data: { "interfaceName": interfaceName, "inputClass": inputClass, "inputString": input},              
 90                 success: function (msg) {
 91                     var jsonstring = JSON.stringify(msg);
 92                     $("#result").val(jsonstring);
 93                 }
 94             });
 95         };
 96 
 97         //函数名得到输入输出值
 98 
 99         function GetFunData(methods) {
100             $.ajax({
101                 type: "POST",
102                 async: false,
103                 url: "/Interface/GetFunData",
104                 data: { "methods": methods },
105                 //data: { "email": interfaceName, "password": input },
106                 success: function (msg) {
107                     $("#input").val(msg.input);
108                     $("#output").val(msg.output);
109                 }
110             });
111         }
112 
113 
114     
115     </script>
116 </head>
117 <body>
118     <h1 style="text-align: center">
119         接口测试界面</h1>
120     <div id="hd" style="color: Red">
121         注:如果没有输入参数或示例,请刷新下页面重试</br>(红色字体表示没实现此接口)
122     </div>
123     <div id="bd" class="clearfix">
124         <div class="right">
125             <div class="content">
126                 接 口:<input id="key" type="text" /><label id="dest"></label></br> 地 址:<input id="address"
127                     type="text" style=" 350px" /></br><span style="vertical-align: top">输 入:</span><textarea
128                         id="input" rows="4" style=" 1000px;"></textarea></br> <span style="vertical-align: top">
129                             输 出:</span><textarea rows="11" id="result" style=" 1000px;"></textarea></br>
130                 <span style="vertical-align: top">示 例:</span><textarea id="output" rows="8" style=" 1000px;"
131                     readonly="readonly"></textarea></br>
132                 <input type="button" onclick="submitTest()" value="提交" />
133                 <a target="_blank" href="http://jsonlint.com/">JSON 格式验证地址</a>
134             </div>
135         </div>
136         <div class="left">
137             函数列表:
138             @{
139                 foreach (CommentAjaxInterfaceText.comment.InputTemple item in Model)
140                 {
141                     if (item.enabled)
142                     {
143                 <p inputClass="@item.inputClass">
144                     <span>@item.description </span><span>@item.methods</span></p> 
145                     }
146                     else
147                     {
148                 <p inputClass="@item.inputClass">
149                     <span style="color: Red">@item.description </span><span>@item.methods</span></p> 
150                     }
151                 }
152             }
153         </div>
154     </div>
155     <div id="ft">
156     </div>
157 </body>
158 </html>

源码下载

 

原文地址:https://www.cnblogs.com/fengmazi/p/2626371.html