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

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

概述Postman是一个可以轻松测试休息的Web服务的工具. 如果Asp.Net项目正在使用WebApi与WebApi Helppages文档,则可以自动为暴露的静态Web服务生成文档. 这种自动生成的文档是好的,但可以通过添加的可访问性更好地完成. 如何组合这些技术技术来生成可以在Postman中导入的JSON文件? 扩展博客帖子“ Using ApiExplorer to export API i Postman是一个可以轻松测试休息的Web服务的工具.

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

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

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

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

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

/// <summary>///     Based on///     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/// </summary>[RoutePrefix("API/postman")]public class PostmanAPIController : APIController{    /// <summary>    ///     Produce [POSTMAN](http://www.getpostman.com) related responses    /// </summary>    public PostmanAPIController()    {        // exists for documentation purposes    }    private Readonly Regex _pathVariableRegEx = new Regex("\{([A-Za-z0-9-_]+)\}",RegexOptions.ECMAScript | RegexOptions.Compiled);    private Readonly Regex _urlParameterVariableRegEx = new Regex("=\{([A-Za-z0-9-_]+)\}",RegexOptions.ECMAScript | RegexOptions.Compiled);    /// <summary>    ///     Get a postman collection of all visible API    ///     (Get the [POSTMAN](http://www.getpostman.com) Chrome extension)    /// </summary>    /// <returns>object describing a POSTMAN collection</returns>    /// <remarks>Get a postman collection of all visible API</remarks>    [httpGet]    [Route(name = "GetPostmanCollection")]    [ResponseType(typeof (PostmanCollectionGet))]    public IhttpActionResult GetPostmanCollection()    {        return Ok(this.PostmanCollectionForController());    }    private PostmanCollectionGet PostmanCollectionForController()    {        var requestUri = Request.RequestUri;        var baseUri = requestUri.Scheme + "://" + requestUri.Host + ":" + requestUri.Port                      + httpContext.Current.Request.ApplicationPath;        var postManCollection = new PostmanCollectionGet                                {                                    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]"                                };        var helpPageSampleGenerator = Configuration.GetHelpPageSampleGenerator();        var APIExplorer = Configuration.Services.GetAPIExplorer();        var APIDescriptionsByController = APIExplorer.APIDescriptions.GroupBy(            description =>            description.ActionDescriptor.ActionBinding.ActionDescriptor.ControllerDescriptor.ControllerType);        foreach (var APIDescriptionsByControllerGroup in APIDescriptionsByController)        {            var controllername = APIDescriptionsByControllerGroup.Key.name.Replace("Controller",string.Empty);            var postManFolder = new PostmanFolderGet                                {                                    ID = GuID.NewGuID(),CollectionID = postManCollection.ID,name = controllername,Description = string.Format("API Methods for {0}",controllername),Collectionname = "API",Order = new Collection<GuID>()                                };            foreach (var APIDescription in APIDescriptionsByControllerGroup                .OrderBy(description => description.httpMethod,new httpMethodComparator())                .ThenBy(description => description.relativePath)                .ThenBy(description => description.documentation.ToString(CultureInfo.InvariantCulture)))            {                TextSample sampleData = null;                var sampleDictionary = helpPageSampleGenerator.GetSample(APIDescription,SampleDirection.Request);                MediaTypeheaderValue mediaTypeheader;                if (MediaTypeheaderValue.TryParse("application/Json",out mediaTypeheader)                    && sampleDictionary.ContainsKey(mediaTypeheader))                {                    sampleData = sampleDictionary[mediaTypeheader] as TextSample;                }                // scrub curly braces from url parameter values                var cleanedUrlParameterUrl = this._urlParameterVariableRegEx.Replace(APIDescription.relativePath,"=-value");                // get pat variables from url                var pathVariables = this._pathVariableRegEx.Matches(cleanedUrlParameterUrl)                                        .Cast<Match>()                                        .Select(m => m.Value)                                        .Select(s => s.Substring(1,s.Length - 2))                                        .ToDictionary(s => s,s => string.Format("{0}-value",s));                // change format of parameters within string to be colon prefixed rather than curly brace wrapped                var postmanReadyUrl = this._pathVariableRegEx.Replace(cleanedUrlParameterUrl,":");                // prefix url with base uri                var url = baseUri.TrimEnd('/') + "/" + postmanReadyUrl;                var request = new PostmanRequestGet                              {                                  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                                             ? null                                             : sampleData.Text,DataMode = "raw",Time = postManCollection.Timestamp,DescriptionFormat = "markdown",Version = "beta",Responses = new Collection<string>(),PathVariables = pathVariables                              };                postManFolder.Order.Add(request.ID); // add to the folder                postManCollection.Requests.Add(request);            }            postManCollection.Folders.Add(postManFolder);        }        return postManCollection;    }}/// <summary>///     Quick comparer for ordering http methods for display/// </summary>internal class httpMethodComparator : IComparer<httpMethod>{    private Readonly string[] _order =    {        "GET","POST","PUT","DELETE"    };    public int Compare(httpMethod x,httpMethod y)    {        return Array.IndexOf(this._order,x.ToString()).Compareto(Array.IndexOf(this._order,y.ToString()));    }}

并生成正确的模型:

一个用于PostManCollection

/// <summary>///     [Postman](http://getpostman.com) collection representation/// </summary>public class PostmanCollectionGet{    /// <summary>    ///     ID of collection    /// </summary>    [JsonProperty(Propertyname = "ID")]    public GuID ID { get; set; }    /// <summary>    ///     name of collection    /// </summary>    [JsonProperty(Propertyname = "name")]    public string name { get; set; }    /// <summary>    ///     Collection generation time    /// </summary>    [JsonProperty(Propertyname = "timestamp")]    public long Timestamp { get; set; }    /// <summary>    ///     Requests associated with the collection    /// </summary>    [JsonProperty(Propertyname = "requests")]    public ICollection<PostmanRequestGet> Requests { get; set; }    /// <summary>    ///     **unused always false**    /// </summary>    [JsonProperty(Propertyname = "synced")]    public bool Synced { get; set; }    /// <summary>    ///     folders within the collection    /// </summary>    [JsonProperty(Propertyname = "folders")]    public ICollection<PostmanFolderGet> Folders { get; set; }    /// <summary>    ///     Description of collection    /// </summary>    [JsonProperty(Propertyname = "description")]    public string Description { get; set; }}

一个邮递员

/// <summary>///     Object that describes a [Postman](http://getpostman.com) folder/// </summary>public class PostmanFolderGet{    /// <summary>    ///     ID of the folder    /// </summary>    [JsonProperty(Propertyname = "ID")]    public GuID ID { get; set; }    /// <summary>    ///     folder name    /// </summary>    [JsonProperty(Propertyname = "name")]    public string name { get; set; }    /// <summary>    ///     folder description    /// </summary>    [JsonProperty(Propertyname = "description")]    public string Description { get; set; }    /// <summary>    ///     ordered List of IDs of items in folder    /// </summary>    [JsonProperty(Propertyname = "order")]    public ICollection<GuID> Order { get; set; }    /// <summary>    ///     name of the collection    /// </summary>    [JsonProperty(Propertyname = "collection_name")]    public string Collectionname { get; set; }    /// <summary>    ///     ID of the collection    /// </summary>    [JsonProperty(Propertyname = "collection_ID")]    public GuID CollectionID { get; set; }}

最后一个PostmanRequest的模型

/// <summary>///     [Postman](http://getpostman.com) request object/// </summary>public class PostmanRequestGet{    /// <summary>    ///     ID of request    /// </summary>    [JsonProperty(Propertyname = "ID")]    public GuID ID { get; set; }    /// <summary>    ///     headers associated with the request    /// </summary>    [JsonProperty(Propertyname = "headers")]    public string headers { get; set; }    /// <summary>    ///     url of the request    /// </summary>    [JsonProperty(Propertyname = "url")]    public string Url { get; set; }    /// <summary>    ///     path variables of the request    /// </summary>    [JsonProperty(Propertyname = "pathVariables")]    public Dictionary<string,string> PathVariables { get; set; }    /// <summary>    ///     method of request    /// </summary>    [JsonProperty(Propertyname = "method")]    public string Method { get; set; }    /// <summary>    ///     data to be sent with the request    /// </summary>    [JsonProperty(Propertyname = "data")]    public string Data { get; set; }    /// <summary>    ///     data mode of reqeust    /// </summary>    [JsonProperty(Propertyname = "dataMode")]    public string DataMode { get; set; }    /// <summary>    ///     name of request    /// </summary>    [JsonProperty(Propertyname = "name")]    public string name { get; set; }    /// <summary>    ///     request description    /// </summary>    [JsonProperty(Propertyname = "description")]    public string Description { get; set; }    /// <summary>    ///     format of description    /// </summary>    [JsonProperty(Propertyname = "descriptionFormat")]    public string DescriptionFormat { get; set; }    /// <summary>    ///     time that this request object was generated    /// </summary>    [JsonProperty(Propertyname = "time")]    public long Time { get; set; }    /// <summary>    ///     version of the request object    /// </summary>    [JsonProperty(Propertyname = "version")]    public string Version { get; set; }    /// <summary>    ///     request response    /// </summary>    [JsonProperty(Propertyname = "responses")]    public ICollection<string> Responses { get; set; }    /// <summary>    ///     the ID of the collection that the request object belongs to    /// </summary>    [JsonProperty(Propertyname = "collection-ID")]    public GuID CollectionID { get; set; }    /// <summary>    ///     Synching    /// </summary>    [JsonProperty(Propertyname = "synced")]    public bool Synced { get; set; }}

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

总结

以上是内存溢出为你收集整理的c# – 如何使用适合导入的WebApi HelpPages从WebApi2项目生成JSON Postman集合全部内容,希望文章能够帮你解决c# – 如何使用适合导入的WebApi HelpPages从WebApi2项目生成JSON Postman集合所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1262880.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-08
下一篇 2022-06-08

发表评论

登录后才能评论

评论列表(0条)

保存