9

Postman은 편안한 웹 서비스를 쉽게 테스트하는 데 사용할 수있는 도구입니다.가져 오기에 적합한 WebApi HelpPages를 사용하여 WebApi2 프로젝트에서 JSON Postman Collections를 생성하는 방법

Asp.Net 프로젝트가 WebApi Helppages과 함께 WebApi과 함께 사용되면 노출 된 안정된 웹 서비스를 위해 자동으로 문서를 생성 할 수 있습니다.

이 자동 생성 문서는 좋지만 추가 된 접근성을 통해 향상시킬 수 있습니다.

우체국에서 가져올 수있는 JSON 파일을 생성하기 위해 이러한 기술을 어떻게 결합 할 수 있습니까?

답변

13

블로그 게시물 "Using ApiExplorer to export API information to PostMan, a Chrome extension for testing Web APIs"을 확장하면 테스트 및 문서화에 사용하기 위해 우편 배달부로 가져올 수있는 JSON 파일을 생성 할 수 있습니다. PostmanFolder에 대한

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; } 
} 

하나 :

먼저 당신은 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, "=$1-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, ":$1"); 

       // 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, 
            Synced = false, 
            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())); 
    } 
} 

을 수출하고 적절한 모델을 생성 할 수 설정 AA 컨트롤러에 필요

01 23,516,
/// <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/우편 배달부에 GET 요청을하고 당신은 형태로 최신 편안한 API를해야합니다 우편 배달부가 읽을 수 있습니다.

+0

'GetHelpPageSampleGenerator() '는 어디에서 가져 왔습니까? NuGet 패키지가 있습니까? 나는 잠재적 인 후보자 [여기]를 발견했다. (https://github.com/flextry/Telerik-Academy/tree/master/Programming%20with%20C%23/0.%20Exams/Telerik%202013-2014%20-%20Web % 20Services % 20 % 26 % 20Cloud/Web % 20Services % 20 % 26 % 20Cloud % 20- % 20Exam % 20Preparation/ForumSystem.Web/Areas/HelpPage/SampleGeneration). – mason

+0

맞음, Microsoft ASP.NET 웹 API 2.2 도움말 페이지 https://www.nuget.org/packages/Microsoft.AspNet.WebApi.Help 페이지 – rheone

+0

을 사용하고 있습니다. 약간 변경해야했지만 NullReferenceException이 발생했습니다. 'PostmanCollectionForController()'에 있습니다. '.ThenBy (description => description.Documentation.ToString (CultureInfo.InvariantCulture)) ' – mason

1

이 기능을 사용하려면 PostmanRequestGet.cs 모델을 업데이트해야합니다.

갱신은 다음과 같습니다 : -

/// <summary> 
     ///  the id of the collection that the request object belongs to 
     /// </summary> 
     [JsonProperty(PropertyName = "collectionId")] 
     public Guid CollectionId { get; set; } 
+2

나는 이것이 당신이 말하는 대답에 대한 논평이어야한다고 생각한다. –

0

왜 표준 자신감을 사용하고 우체부로 사용하지?

  1. Swagger 무엇입니까? 이 solution은 다음과 같습니다 비주얼 스튜디오 (나머지 웹 API 문서와 클라이언트 인 에이 블러)
  2. Importing Swagger files to Postman
  3. 사용 Swashbuckle NuGet 패키지는 API (설치 패키지 Swashbuckle - 전)

이 보너스에 대한 자신감을 생성하는 ASP.NET 코어 레스트에서 지원 WebAPI

+1

질문에 대답 할 때, 나는 실수 할 수도 있지만, 우편 배달부는 맹 글씨 파일을 읽지 않았다. 비록 이것을 ASP.NET 4.x에서 개발 된 여러 웹 API 프로젝트 중 하나에 대한 현재 접근 방식으로 사용합니다. 그럼에도 불구하고 방대한 접근법은 호환되지 않는 라이센스가있는 추가 라이브러리를 사용해야합니다. 마찬가지로 Swashbuckle 구현은 비록 더 많은 기능적으로 기능이 풍부 할지라도 위조 된 사양으로 다루지 않은 Postman 특정 기능을 갖춘 위에서 언급 한 솔루션과 같이 세분화 된/낮은 수준의 제어 기능을 제공하지 않습니다. – rheone

+0

일부 사람들에게는 나 자신을 포함하여 미래의 참고 문헌에 대한 대답으로 제시되기에 충분합니다. – hB0