c# – 如何使用适合导入的WebApi HelpPages从WebApi2项目生成JSON Postman集合

前端之家收集整理的这篇文章主要介绍了c# – 如何使用适合导入的WebApi HelpPages从WebApi2项目生成JSON Postman集合前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
Postman是一个可以轻松测试休息的Web服务的工具.

如果Asp.Net项目正在使用WebApiWebApi Helppages文档,则可以自动为暴露的静态Web服务生成文档.

这种自动生成的文档是好的,但可以通过添加的可访问性更好地完成.

如何组合这些技术技术来生成可以在Postman中导入的JSON文件

解决方法

扩展博客帖子“ Using ApiExplorer to export API information to PostMan,a Chrome extension for testing Web APIs”可以生成一个可以导入Postman的JSON文件,用于测试和记录.

首先,您需要设置一个可以导出JSON的控制器

  1. /// <summary>
  2. /// Based on
  3. /// http://blogs.msdn.com/b/yaohuang1/archive/2012/06/15/using-apiexplorer-to-export-api-information-to-postman-a-chrome-extension-for-testing-web-apis.aspx
  4. /// </summary>
  5. [RoutePrefix("api/postman")]
  6. public class PostmanApiController : ApiController
  7. {
  8. /// <summary>
  9. /// Produce [POSTMAN](http://www.getpostman.com) related responses
  10. /// </summary>
  11. public PostmanApiController()
  12. {
  13. // exists for documentation purposes
  14. }
  15.  
  16. private readonly Regex _pathVariableRegEx = new Regex("\\{([A-Za-z0-9-_]+)\\}",RegexOptions.ECMAScript | RegexOptions.Compiled);
  17. private readonly Regex _urlParameterVariableRegEx = new Regex("=\\{([A-Za-z0-9-_]+)\\}",RegexOptions.ECMAScript | RegexOptions.Compiled);
  18.  
  19. /// <summary>
  20. /// Get a postman collection of all visible Api
  21. /// (Get the [POSTMAN](http://www.getpostman.com) chrome extension)
  22. /// </summary>
  23. /// <returns>object describing a POSTMAN collection</returns>
  24. /// <remarks>Get a postman collection of all visible api</remarks>
  25. [HttpGet]
  26. [Route(Name = "GetPostmanCollection")]
  27. [ResponseType(typeof (PostmanCollectionGet))]
  28. public IHttpActionResult GetPostmanCollection()
  29. {
  30. return Ok(this.PostmanCollectionForController());
  31. }
  32.  
  33. private PostmanCollectionGet PostmanCollectionForController()
  34. {
  35. var requestUri = Request.RequestUri;
  36. var baseUri = requestUri.Scheme + "://" + requestUri.Host + ":" + requestUri.Port
  37. + HttpContext.Current.Request.ApplicationPath;
  38.  
  39. var postManCollection = new PostmanCollectionGet
  40. {
  41. Id = Guid.NewGuid(),Name = "[Name of your API]",Timestamp = DateTime.Now.Ticks,Requests = new Collection<PostmanRequestGet>(),Folders = new Collection<PostmanFolderGet>(),Synced = false,Description = "[Description of your API]"
  42. };
  43.  
  44.  
  45. var helpPageSampleGenerator = Configuration.GetHelpPageSampleGenerator();
  46.  
  47. var apiExplorer = Configuration.Services.GetApiExplorer();
  48.  
  49. var apiDescriptionsByController = apiExplorer.ApiDescriptions.GroupBy(
  50. description =>
  51. description.ActionDescriptor.ActionBinding.ActionDescriptor.ControllerDescriptor.ControllerType);
  52.  
  53. foreach (var apiDescriptionsByControllerGroup in apiDescriptionsByController)
  54. {
  55. var controllerName = apiDescriptionsByControllerGroup.Key.Name.Replace("Controller",string.Empty);
  56.  
  57. var postManFolder = new PostmanFolderGet
  58. {
  59. Id = Guid.NewGuid(),CollectionId = postManCollection.Id,Name = controllerName,Description = string.Format("Api Methods for {0}",controllerName),CollectionName = "api",Order = new Collection<Guid>()
  60. };
  61.  
  62. foreach (var apiDescription in apiDescriptionsByControllerGroup
  63. .OrderBy(description => description.HttpMethod,new HttpMethodComparator())
  64. .ThenBy(description => description.RelativePath)
  65. .ThenBy(description => description.Documentation.ToString(CultureInfo.InvariantCulture)))
  66. {
  67. TextSample sampleData = null;
  68. var sampleDictionary = helpPageSampleGenerator.GetSample(apiDescription,SampleDirection.Request);
  69. MediaTypeHeaderValue mediaTypeHeader;
  70. if (MediaTypeHeaderValue.TryParse("application/json",out mediaTypeHeader)
  71. && sampleDictionary.ContainsKey(mediaTypeHeader))
  72. {
  73. sampleData = sampleDictionary[mediaTypeHeader] as TextSample;
  74. }
  75.  
  76. // scrub curly braces from url parameter values
  77. var cleanedUrlParameterUrl = this._urlParameterVariableRegEx.Replace(apiDescription.RelativePath,"=$1-value");
  78.  
  79. // get pat variables from url
  80. var pathVariables = this._pathVariableRegEx.Matches(cleanedUrlParameterUrl)
  81. .Cast<Match>()
  82. .Select(m => m.Value)
  83. .Select(s => s.Substring(1,s.Length - 2))
  84. .ToDictionary(s => s,s => string.Format("{0}-value",s));
  85.  
  86. // change format of parameters within string to be colon prefixed rather than curly brace wrapped
  87. var postmanReadyUrl = this._pathVariableRegEx.Replace(cleanedUrlParameterUrl,":$1");
  88.  
  89. // prefix url with base uri
  90. var url = baseUri.TrimEnd('/') + "/" + postmanReadyUrl;
  91.  
  92. var request = new PostmanRequestGet
  93. {
  94. CollectionId = postManCollection.Id,Id = Guid.NewGuid(),Name = apiDescription.RelativePath,Description = apiDescription.Documentation,Url = url,Method = apiDescription.HttpMethod.Method,Headers = "Content-Type: application/json",Data = sampleData == null
  95. ? null
  96. : sampleData.Text,DataMode = "raw",Time = postManCollection.Timestamp,DescriptionFormat = "markdown",Version = "beta",Responses = new Collection<string>(),PathVariables = pathVariables
  97. };
  98.  
  99. postManFolder.Order.Add(request.Id); // add to the folder
  100. postManCollection.Requests.Add(request);
  101. }
  102.  
  103. postManCollection.Folders.Add(postManFolder);
  104. }
  105.  
  106. return postManCollection;
  107. }
  108. }
  109.  
  110. /// <summary>
  111. /// Quick comparer for ordering http methods for display
  112. /// </summary>
  113. internal class HttpMethodComparator : IComparer<HttpMethod>
  114. {
  115. private readonly string[] _order =
  116. {
  117. "GET","POST","PUT","DELETE"
  118. };
  119.  
  120. public int Compare(HttpMethod x,HttpMethod y)
  121. {
  122. return Array.IndexOf(this._order,x.ToString()).CompareTo(Array.IndexOf(this._order,y.ToString()));
  123. }
  124. }

生成正确的模型:

一个用于PostManCollection

  1. /// <summary>
  2. /// [Postman](http://getpostman.com) collection representation
  3. /// </summary>
  4. public class PostmanCollectionGet
  5. {
  6. /// <summary>
  7. /// Id of collection
  8. /// </summary>
  9. [JsonProperty(PropertyName = "id")]
  10. public Guid Id { get; set; }
  11.  
  12. /// <summary>
  13. /// Name of collection
  14. /// </summary>
  15. [JsonProperty(PropertyName = "name")]
  16. public string Name { get; set; }
  17.  
  18. /// <summary>
  19. /// Collection generation time
  20. /// </summary>
  21. [JsonProperty(PropertyName = "timestamp")]
  22. public long Timestamp { get; set; }
  23.  
  24. /// <summary>
  25. /// Requests associated with the collection
  26. /// </summary>
  27. [JsonProperty(PropertyName = "requests")]
  28. public ICollection<PostmanRequestGet> Requests { get; set; }
  29.  
  30. /// <summary>
  31. /// **unused always false**
  32. /// </summary>
  33. [JsonProperty(PropertyName = "synced")]
  34. public bool Synced { get; set; }
  35.  
  36. /// <summary>
  37. /// folders within the collection
  38. /// </summary>
  39. [JsonProperty(PropertyName = "folders")]
  40. public ICollection<PostmanFolderGet> Folders { get; set; }
  41.  
  42. /// <summary>
  43. /// Description of collection
  44. /// </summary>
  45. [JsonProperty(PropertyName = "description")]
  46. public string Description { get; set; }
  47. }

一个邮递员

  1. /// <summary>
  2. /// Object that describes a [Postman](http://getpostman.com) folder
  3. /// </summary>
  4. public class PostmanFolderGet
  5. {
  6. /// <summary>
  7. /// id of the folder
  8. /// </summary>
  9. [JsonProperty(PropertyName = "id")]
  10. public Guid Id { get; set; }
  11.  
  12. /// <summary>
  13. /// folder name
  14. /// </summary>
  15. [JsonProperty(PropertyName = "name")]
  16. public string Name { get; set; }
  17.  
  18. /// <summary>
  19. /// folder description
  20. /// </summary>
  21. [JsonProperty(PropertyName = "description")]
  22. public string Description { get; set; }
  23.  
  24. /// <summary>
  25. /// ordered list of ids of items in folder
  26. /// </summary>
  27. [JsonProperty(PropertyName = "order")]
  28. public ICollection<Guid> Order { get; set; }
  29.  
  30. /// <summary>
  31. /// Name of the collection
  32. /// </summary>
  33. [JsonProperty(PropertyName = "collection_name")]
  34. public string CollectionName { get; set; }
  35.  
  36. /// <summary>
  37. /// id of the collection
  38. /// </summary>
  39. [JsonProperty(PropertyName = "collection_id")]
  40. public Guid CollectionId { get; set; }
  41. }

最后一个PostmanRequest的模型

  1. /// <summary>
  2. /// [Postman](http://getpostman.com) request object
  3. /// </summary>
  4. public class PostmanRequestGet
  5. {
  6. /// <summary>
  7. /// id of request
  8. /// </summary>
  9. [JsonProperty(PropertyName = "id")]
  10. public Guid Id { get; set; }
  11.  
  12. /// <summary>
  13. /// headers associated with the request
  14. /// </summary>
  15. [JsonProperty(PropertyName = "headers")]
  16. public string Headers { get; set; }
  17.  
  18. /// <summary>
  19. /// url of the request
  20. /// </summary>
  21. [JsonProperty(PropertyName = "url")]
  22. public string Url { get; set; }
  23.  
  24. /// <summary>
  25. /// path variables of the request
  26. /// </summary>
  27. [JsonProperty(PropertyName = "pathVariables")]
  28. public Dictionary<string,string> PathVariables { get; set; }
  29.  
  30. /// <summary>
  31. /// method of request
  32. /// </summary>
  33. [JsonProperty(PropertyName = "method")]
  34. public string Method { get; set; }
  35.  
  36. /// <summary>
  37. /// data to be sent with the request
  38. /// </summary>
  39. [JsonProperty(PropertyName = "data")]
  40. public string Data { get; set; }
  41.  
  42. /// <summary>
  43. /// data mode of reqeust
  44. /// </summary>
  45. [JsonProperty(PropertyName = "dataMode")]
  46. public string DataMode { get; set; }
  47.  
  48. /// <summary>
  49. /// name of request
  50. /// </summary>
  51. [JsonProperty(PropertyName = "name")]
  52. public string Name { get; set; }
  53.  
  54. /// <summary>
  55. /// request description
  56. /// </summary>
  57. [JsonProperty(PropertyName = "description")]
  58. public string Description { get; set; }
  59.  
  60. /// <summary>
  61. /// format of description
  62. /// </summary>
  63. [JsonProperty(PropertyName = "descriptionFormat")]
  64. public string DescriptionFormat { get; set; }
  65.  
  66. /// <summary>
  67. /// time that this request object was generated
  68. /// </summary>
  69. [JsonProperty(PropertyName = "time")]
  70. public long Time { get; set; }
  71.  
  72. /// <summary>
  73. /// version of the request object
  74. /// </summary>
  75. [JsonProperty(PropertyName = "version")]
  76. public string Version { get; set; }
  77.  
  78. /// <summary>
  79. /// request response
  80. /// </summary>
  81. [JsonProperty(PropertyName = "responses")]
  82. public ICollection<string> Responses { get; set; }
  83.  
  84. /// <summary>
  85. /// the id of the collection that the request object belongs to
  86. /// </summary>
  87. [JsonProperty(PropertyName = "collection-id")]
  88. public Guid CollectionId { get; set; }
  89.  
  90. /// <summary>
  91. /// Synching
  92. /// </summary>
  93. [JsonProperty(PropertyName = "synced")]
  94. public bool Synced { get; set; }
  95. }

现在您需要做的就是向[应用程序] api / postman发出GET请求,并且您将以Postman可读的形式使用最新的安全API.

猜你在找的C#相关文章