码迷,mamicode.com
首页 > Windows程序 > 详细

WebAPI生成可导入到PostMan的数据

时间:2015-06-11 10:56:51      阅读:413      评论:0      收藏:0      [点我收藏+]

标签:

一、前言

现在使用WebAPI来作为实现企业服务化的需求非常常见,不可否认它也是很便于使用的,基于注释可以生成对应的帮助文档(Microsoft.AspNet.WebApi.HelpPage),但是比较便利和可持久化的调试官方却没有相应的集成,虽然我们可以使  用诸如Fiddler、Swagger、PostMan、及其他手写代码的方式等等来调试我们的WebAPI,但是却依然不是很方便,对于公司来说也需要有一种可以统一、可持久化、且行之有效的规范。

调试接口我希望他能达到以下3点:

1:可根据接口定义生成测试数据。

2:测试数据可持久化,便于持续迭代。

3:测试数据可共享。文本主要介绍如何利用PostMan实现这3点。

二、有哪些调试方法

目前所知道的调试方式有:

1:耳熟能详的Fiddler就不说了,功能非常强大,但不是我们想要的。

2:PostMan,使用方便且满足上面的2和3,这是一个谷歌插件(地址在这),也有App版本(https://www.getpostman.com/)推荐。

3:Swagger,已有人将其结合SwaggerUI集成到WebAPI中,Nuget上安装

  1. install-package Swashbuckle  

即可,项目地址https://github.com/domaindrivendev/Swashbuckle

4:手写HttpClient来实现,其他的还有https://github.com/wuchang/WebApiTestClient

以上这几种方法比较推荐的自然是PostMan。

三、PostMan的基本操作

我们先来看看使用PosMan的一些基本操作。

如下所示,我们定义了几个简单的方法来作为我们调试的接口。

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web.Http;  
  5. using WebAPI2PostMan.Models;  
  6.   
  7. namespace WebAPI2PostMan.Controllers  
  8. {  
  9.     /// <summary>  
  10.     ///     产品服务  
  11.     /// </summary>  
  12.     [RoutePrefix("Product")]  
  13.     public class ProductController : ApiController  
  14.     {  
  15.         private static readonly List<Product> Products = new List<Product>  
  16.         {  
  17.             new Product{Id = Guid.NewGuid(), Description = "产品描述",Name = "产品名称",Price = 123},  
  18.             new Product{Id = Guid.NewGuid(), Description = "产品描述",Name = "产品名称",Price = 124},  
  19.             new Product{Id = Guid.NewGuid(), Description = "产品描述",Name = "产品名称",Price = 125},  
  20.             new Product{Id = Guid.NewGuid(), Description = "产品描述",Name = "产品名称",Price = 126}  
  21.         };  
  22.   
  23.         /// <summary>  
  24.         ///     获取所有产品  
  25.         /// </summary>  
  26.         [HttpGet, Route("All")]  
  27.         public IEnumerable<Product> Get()  
  28.         {  
  29.             return Products;  
  30.         }  
  31.   
  32.         /// <summary>  
  33.         ///     获取产品  
  34.         /// </summary>  
  35.         /// <param name="id">产品编号</param>  
  36.         [HttpGet, Route("{id}")]  
  37.         public string Get(Guid id)  
  38.         {  
  39.             return "value";  
  40.         }  
  41.   
  42.         /// <summary>  
  43.         ///     添加产品  
  44.         /// </summary>  
  45.         /// <param name="request">产品请求</param>  
  46.         [HttpPost, Route("")]  
  47.         public string Post(Product request)  
  48.         {  
  49.             Products.Add(request);  
  50.             return "ok";  
  51.         }  
  52.         /// <summary>  
  53.         ///     编辑产品  
  54.         /// </summary>  
  55.         /// <param name="id">产品编号</param>  
  56.         /// <param name="request">编辑后的产品</param>  
  57.         [HttpPut, Route("{id}")]  
  58.         public void Put(int id, Product request)  
  59.         {  
  60.         }  
  61.         /// <summary>  
  62.         ///     删除产品  
  63.         /// </summary>  
  64.         /// <param name="id">产品编号</param>  
  65.         [HttpDelete, Route("{id}")]  
  66.         public string Delete(Guid id)  
  67.         {  
  68.             var model = Products.FirstOrDefault(x => x.Id.Equals(id));  
  69.             Products.Remove(model);  
  70.             var result = string.Format("编号为{0}的产品删除成功!", id);  
  71.             return result;  
  72.         }  
  73.     }  
  74. }  

在Nuget里添加了Microsoft.AspNet.WebApi.HelpPage之后生成的帮助文档如下图。

技术分享

接下来,我们使用PostMan来调试我们定义的接口。在这里我使用插件版的PostMan作为演示。

获取所有产品这种其实直接使用浏览器访问就可以达到调试的目的,但是若有特殊Header或身份验证时就不太方便了,如下在PostMan中输入对应地址点击【Send】即可看到返回的数据及消耗的时间和HttpStatus等。

技术分享

对于我们常用的我们可以点击Add to collection将其加入到Collections中便于下次测试。

技术分享

技术分享

接下来,我们对新增产品添加调试。

技术分享

其余的类似,请求的方法类型与Http请求类型一致。

技术分享

四、生成PostMan导入数据

那么,对于参数较多的接口时第一次添加参数是比较繁琐的,所以我希望能有根据接口定义生成出可以导入到PostMan中的方法,分析Postman下载出来的数据格式可见其实就是一个Json格式的文件。

技术分享

技术分享

那既然是Json格式的文件,我们就可以根据它所需要的格式生成。首先我们定义出需要的类,并没有包含全部的属性,APP版本有一些是否同步等属性并没有加进来,有兴趣的朋友可以研究一下。

  1. public class PostmanCollection  
  2.  {  
  3.      public string id { get; set; }  
  4.      public string name { get; set; }  
  5.      public string description { get; set; }  
  6.      public List<string> order { get; set; }  
  7.      public long timestamp { get; set; }  
  8.      public List<PostmanRequest> requests { get; set; }  
  9.  }  
  10.   
  11.  public class PostmanRequest  
  12.  {  
  13.      public string collection { get; set; }  
  14.      public string id { get; set; }  
  15.      public string name { get; set; }  
  16.      public string dataMode { get; set; }  
  17.      public List<PostmanData> data { get; set; }  
  18.      public string description { get; set; }  
  19.      public string descriptionFormat { get; set; }  
  20.      public string headers { get; set; }  
  21.      public string method { get; set; }  
  22.      public Dictionary<string, string> pathVariables { get; set; }  
  23.      public string url { get; set; }  
  24.      public int version { get; set; }  
  25.      public string collectionId { get; set; }  
  26.  }  
  27.   
  28.  public class PostmanData  
  29.  {  
  30.      public string key { get; set; }  
  31.      public string value { get; set; }  
  32.      public string type {  
  33.          get { return "text"; }  
  34.      }  
  35.      public bool enabled {  
  36.          get { return true; }  
  37.      }  
  38.  }  

PostMan支持从地址导入,所以我们可以定义个PostManController要根据接口定义来生成我们的Json数据。

  1. using System.Collections.Generic;  
  2. using System.Linq;  
  3. using System.Web.Http;  
  4. using System.Web.Http.Description;  
  5. using System.Web.Http.Results;  
  6. using Newtonsoft.Json;  
  7. using WebAPI2PostMan.Areas.HelpPage;  
  8. using WebAPI2PostMan.Models;  
  9.   
  10. namespace WebAPI2PostMan.Controllers  
  11. {  
  12.     /// <summary>  
  13.     ///   
  14.     /// </summary>  
  15.     [RoutePrefix("PostMan")]  
  16.     public class PostManController : ApiController  
  17.     {  
  18.         private const string Host = "http://localhost:11488/";  
  19.   
  20.         /// <summary>  
  21.         ///     获取PostMan集合  
  22.         /// </summary>  
  23.         /// <returns></returns>  
  24.         [Route("")]  
  25.         public JsonResult<PostmanCollection> GetPostmanCollection()  
  26.         {  
  27.             var collectionId = PostMan.GetId();  
  28.             var apis = Configuration.Services.GetApiExplorer().ApiDescriptions.Where(x => x.Documentation != null);  
  29.             var requests = GetPostmanRequests(apis, collectionId);  
  30.             var collection = new PostmanCollection  
  31.             {  
  32.                 id = collectionId,  
  33.                 name = "WebAPI2PostMan",  
  34.                 description = "",  
  35.                 order = requests.Select(x => x.id).ToList(),  
  36.                 timestamp = 0,  
  37.                 requests = requests  
  38.             };  
  39.   
  40.             return Json(collection);  
  41.         }  
  42.   
  43.         private List<PostmanRequest> GetPostmanRequests(IEnumerable<ApiDescription> apis, string collectionId)  
  44.         {  
  45.             return apis.Select(api => new PostmanRequest  
  46.             {  
  47.                 collection = collectionId,  
  48.                 id = PostMan.GetId(),  
  49.                 name = api.Documentation,  
  50.                 dataMode = "urlencoded",  
  51.                 data = GetPostmanDatas(api),  
  52.                 description = "",  
  53.                 descriptionFormat = "html",  
  54.                 headers = "",  
  55.                 method = api.HttpMethod.Method,  
  56.                 pathVariables = new Dictionary<string, string>(),  
  57.                 url = Host + api.RelativePath,  
  58.                 version = 2,  
  59.                 collectionId = collectionId  
  60.             }).ToList();  
  61.         }  
  62.   
  63.         private List<PostmanData> GetPostmanDatas(ApiDescription api)  
  64.         {  
  65.             var postmandatas = new List<PostmanData>();  
  66.             var apiModel = Configuration.GetHelpPageApiModel(api.GetFriendlyId());  
  67.             var raw = apiModel.SampleRequests.Values.FirstOrDefault();  
  68.             if (raw == null) return postmandatas;  
  69.             var pdata = JsonConvert.DeserializeObject<Dictionary<string,string>>(raw.ToString());  
  70.             postmandatas.AddRange(pdata.Select(model => new PostmanData {key = model.Key, value = model.Value}));  
  71.             return postmandatas;  
  72.         }  
  73.     }  
  74. }  

主要生成代码就是获取所有接口和接口定义的参数。值得一提的是,我们可以借助Microsoft.AspNet.WebApi.HelpPage来获取SampleRequests,从而使用SampleRequests来填充我们的测试数据。

运行程序访问http://localhost:11488/PostMan 并将其导入到PostMan。

技术分享

技术分享

效果还是可以接受的,还有写可以拓展的地方,比如可以直接一键导入到PostMan程序中,用谷歌浏览器审查元素可以发现导入的方法是importCollectionFromUrl,在console中输入

  1. window.open("chrome-extension://fdmmgilgnpjigdojojpjoooidkmcomcm/index.html");  
  2. pm.collections.importCollectionFromUrl("http://localhost:11488/postman");  

就可以达到一键导入的目的了。但是遗憾的是,必须要在插件内调用才有效,代码匆忙,还有很多地方可以继续拓展,不过本文的目的已经达到了。

示例代码:https://github.com/yanghongjie/WebAPI2PostMan

WebAPI生成可导入到PostMan的数据

标签:

原文地址:http://www.cnblogs.com/jamestuhao/p/4568282.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!