使用动态查询字符串为ASP.NET Web Api方法提供文档

时间:2017-03-09 09:12:57

标签: c# asp.net asp.net-web-api

我正在使用Help Pages for ASP.NET Web API为我们的网络API创建文档。使用XML文档注释一切正常。但是,对于一种方法,我无法弄清楚如何为动态查询字符串提供文档。 该方法使用请求的GetQueryNameValuePairs()来为模型选择查询字符串的键值对。例如,?1=foo&2=bar将生成两个对象的列表,其中Id分别设置为1和2,值分别为'foo'和'bar'。

我已尝试将<param>标记添加到XML注释中,但由于该方法不包含匹配参数,因此会将其忽略。

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

您可以尝试扩展帮助页面生成过程。创建ASP.NET Web API项目时,与帮助页面相关的代码将作为源代码下载,而不是.dll,因此您可以使用您喜欢的任何自定义逻辑对其进行扩展。

这就是我要做的事情:

  1. 创建一个attribute类并用它装饰我的特殊方法(例如[DynamicQueryParameter("Param1",typeof(string))]
  2. 修改HelPageConfigurationExtensions.cs以从操作中查询这些属性,并手动将其添加到模型的UriParameters集合中。我可能会在GenerateUriParameters()方法中执行此操作。
  3. [编辑]我实际上有一些时间,所以我自己把解决方案放在一起,因为,你知道,这很有趣:)

    所以创建一个attribute

    public class DynamicUriParameterAttribute : Attribute
    {
        public string Name { get; set; }
        public Type Type { get; set; }
        public string Description { get; set; }
    }
    

    您可以使用以下方法修饰您的操作方法:

    [DynamicUriParameter(Description = "Some description", Name ="Some name", Type =typeof(string))]
    public IEnumerable<string> Get()
    {
      return new string[] { "value1", "value2" };
    }
    

    然后我像这样修改了HelpPageConfigurationExtensions.GenerateApiModel()

    private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
    {
       HelpPageApiModel apiModel = new HelpPageApiModel()
       {
          ApiDescription = apiDescription,
       };
    
    
    ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
    HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();            
    GenerateUriParameters(apiModel, modelGenerator);
    
    // add this part
    var attrs = apiDescription.ActionDescriptor.GetCustomAttributes<DynamicUriParameterAttribute>();
    foreach (var attr in attrs)
    {
        apiModel.UriParameters.Add(
           new ParameterDescription
           {
               Name = attr.Name,
               Documentation = attr.Description,
               TypeDescription = modelGenerator.GetOrCreateModelDescription(attr.Type)
           }
         );
      }
      // until here
      GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
      GenerateResourceDescription(apiModel, modelGenerator);
      GenerateSamples(apiModel, sampleGenerator);
    
      return apiModel;
    }