的ASP.NET Web API生成模型的所有参数 - 帮助页面 [英] ASP.NET Web API Generate all parameters from model - help pages

查看:349
本文介绍了的ASP.NET Web API生成模型的所有参数 - 帮助页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很忙,创建一个Web API(里面一个ASP mvc4应用程序)。我使用该库在asp.net网站建议的生成文档(<一个href=\"http://www.asp.net/web-api/overview/creating-web-apis/creating-api-help-pages\">http://www.asp.net/web-api/overview/creating-web-apis/creating-api-help-pages).

I'm busy creating a Web API (Inside a asp mvc4 application). I am using the library suggested on the asp.net site for generating documentation (http://www.asp.net/web-api/overview/creating-web-apis/creating-api-help-pages).

我的问题是,如果我的参数是一个模式,那么我不能指定模型包含在生成的帮助页面什么属性。

My problem is that if my parameter is a model, then I can't specify what properties the model contains in the generated help pages.

下面是一个例子:

MODEL:

public class TestModel
{
    property String FirstName {get;set;}
    property String Surname {get; set;}
    property Boolean Active {get;set;} 
}

ACTION:

ACTION:

/// <summary>
/// This is a test action
/// </summary>
/// <param name="model">this is the model</param> <-- this works
/// <param name="FirstName">This is the first name </param>  <-- doesn't work
/// <param name ="model.Surname">This is the surname</param> <-- doesn't work
public HttpResponseMessage Post(my.namespace.models.TestModel model)
{
  ...
}

仅限于模型参数获取生成。

Only the parameter for model gets generated.

我看了看那个获取的文档生成的XML文档,它确实增加其他参数。

I took a look at the xml document that gets generated for the documentation and it does add the other parameters.

<member name="my.namespace.api.Post(my.namespace.models.TestModel)">
     <summary>
         this is a test action
     </summary>
     <param name="model>this is the model</param>
     <param name="FirstName">This is the first name </param>
     <param name="model.Surname">This is the surname</param>
</member>

但在帮助页面只生成参数模型。

But on the help pages it only generates the parameter model.

我已经追查到它从XML获取参数的方法。

I have traced it down to the method where it gets the parameters from the xml.

Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;

这是坐落在其中自动生成HelpPageConfigurationExtentions.cs。

This is located in the HelpPageConfigurationExtentions.cs which is auto generated.

我在处理这个错误的方式?有谁知道周围的工作的?

Am i approaching this the wrong way? Does anyone know of a work around?

任何建议或解决方案将成为AP preciated。

Any suggestions or solutions will be appreciated.

推荐答案

的MVC的Web API文档功能,通过您的API的类和方法使用反射散步。这将构建文档的结构,但会造成或多或少的空(无用)文档中,除非你已经添加文档注释。

The MVC Web API documentation feature walks through your API classes and methods using reflection. This will build the structure of the documentation but will result in more or less empty (and useless) documentation unless you have added documentation comments.

在文档的主体是使用使用///它有必须遵循特定的结构文档注释生成的XML文件填补。这意味着你不能用你希望它显示,它实际上已经被连接到的东西是你的API中无论充实您的XML,并且必须遵循你的类和属性的结构。

The body of the documentation is filled using the XML file that is generated using /// documentation comments which has a specific structure that must be followed. That means that you can't fill your xml with whatever you want it to display, it actually has to be connected to something that is in your API and must follow the structure of your classes and properties.

所以你的情况,你不能把模型属性文件中的API方法。你必须把它放到那里的属性存在的模式。

So in your case you can't put model property documentation in an api method. You have to put it into the Model where the property exists.

MODEL:

  public class TestModel
  {
  /// <summary>This is the first name </summary>
      property String FirstName {get;set;}
  /// <summary>This is the surname</summary>
      property String Surname {get; set;}
      property Boolean Active {get;set;} 
  }

ACTION:

ACTION:

  /// <summary>
  /// This is a test action
  /// </summary>
  /// <param name="model">this is the model</param> 
  public HttpResponseMessage Post(my.namespace.models.TestModel model)
  {
    ...
  }

修改说明页

这是自动生成不包括模型文档仅API方法都记录默认帮助页面。为了在你的API来显示有关参数的详细信息定制是必需的。随后的指令是添加参数文件的一种方式。

Modify Help Pages

The default Help pages that are automatically generated do not include Model documentation only the api methods are documented. In order to display more information about the parameters in your api a customisation is required. The instruction that follow are one way to add parameter documentation.

创建地区/ HelpPage /模型两种新型

Create two new types in Areas/HelpPage/Models

public class TypeDocumentation
{
    public TypeDocumentation()
    {
        PropertyDocumentation = new Collection<PropertyDocumentation>();
    }

    public string Summary { get; set; }
    public ICollection<PropertyDocumentation> PropertyDocumentation { get; set; } 
}

public class PropertyDocumentation
{
    public PropertyDocumentation(string name, string type, string docs)
    {
        Name = name;
        Type = type;
        Documentation = docs;
    }
    public string Name { get; set; }
    public string Type { get; set; }
    public string Documentation { get; set; }
}

一个新的属性添加到HelpPageApiModel.cs

Add a new property to HelpPageApiModel.cs

public IDictionary<string, TypeDocumentation> ParameterModels{ get; set; } 

创建一个新的接口

Create a new interface

internal interface IModelDocumentationProvider
{
    IDictionary<string, TypeDocumentation> GetModelDocumentation(HttpActionDescriptor actionDescriptor);
}

修改XmlDocumentationProvider实施新界面

Modify XmlDocumentationProvider to implement the new interface

public class XmlDocumentationProvider : IDocumentationProvider, IModelDocumentationProvider
{
    private const string TypeExpression = "/doc/members/member[@name='T:{0}']";
    private const string PropertyExpression = "/doc/members/member[@name='P:{0}']";
///...
///... existing code
///...

    private static string GetPropertyName(PropertyInfo property)
    {
        string name = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", property.DeclaringType.FullName, property.Name);
        return name;
    }

    public IDictionary<string, TypeDocumentation> GetModelDocumentation(HttpActionDescriptor actionDescriptor)
    {
        var retDictionary = new Dictionary<string, TypeDocumentation>();
        ReflectedHttpActionDescriptor reflectedActionDescriptor = actionDescriptor as ReflectedHttpActionDescriptor;
        if (reflectedActionDescriptor != null)
        {
            foreach (var parameterDescriptor in reflectedActionDescriptor.GetParameters())
            {
                if (!parameterDescriptor.ParameterType.IsValueType)
                {
                    TypeDocumentation typeDocs = new TypeDocumentation();


                    string selectExpression = String.Format(CultureInfo.InvariantCulture, TypeExpression, GetTypeName(parameterDescriptor.ParameterType));
                    var typeNode = _documentNavigator.SelectSingleNode(selectExpression);

                    if (typeNode != null)
                    {
                        XPathNavigator summaryNode;
                        summaryNode = typeNode.SelectSingleNode("summary");
                        if (summaryNode != null)
                            typeDocs.Summary = summaryNode.Value;
                    }

                    foreach (var prop in parameterDescriptor.ParameterType.GetProperties())
                    {
                        string propName = prop.Name;
                        string propDocs = string.Empty;
                        string propExpression = String.Format(CultureInfo.InvariantCulture, PropertyExpression, GetPropertyName(prop));
                        var propNode = _documentNavigator.SelectSingleNode(propExpression);
                        if (propNode != null)
                        {
                            XPathNavigator summaryNode;
                            summaryNode = propNode.SelectSingleNode("summary");
                            if (summaryNode != null) propDocs = summaryNode.Value;
                        }
                        typeDocs.PropertyDocumentation.Add(new PropertyDocumentation(propName, prop.PropertyType.Name, propDocs));

                    }
                    retDictionary.Add(parameterDescriptor.ParameterName, typeDocs);
                }

            }

        }

        return retDictionary;
    }
}

添加code到HelpPageConfigurationExtension在GenerateApiModel方法

Add code to HelpPageConfigurationExtension in GenerateApiModel method

IModelDocumentationProvider modelProvider =
            config.Services.GetDocumentationProvider() as IModelDocumentationProvider;
if (modelProvider != null)
{
    apiModel.ParameterModels = modelProvider.GetModelDocumentation(apiDescription.ActionDescriptor);
}

修改HelpPageApiModel.cshtml增加要显示的模型文档以下。

Modify HelpPageApiModel.cshtml adding to following where you want the Model documentation to be displayed.

bool hasModels = Model.ParameterModels.Count > 0;
if (hasModels)
{
     <h2>Parameter Information</h2>
  @Html.DisplayFor(apiModel => apiModel.ParameterModels, "Models")

}

添加到Models.cshtml DisplayTemplates

Add a Models.cshtml to DisplayTemplates

@using System.Web.Http
@using System.Web.Http.Description
@using MvcApplication2.Areas.HelpPage.Models
@model IDictionary<string, TypeDocumentation>

@foreach (var modelType in Model)
{
    <h3>@modelType.Key</h3>
    if (modelType.Value.Summary != null)
    {
    <p>@modelType.Value.Summary</p>
    }
    <table class="help-page-table">
        <thead>
            <tr>
                <th>Property</th>

                <th>Description</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var propInfo in modelType.Value.PropertyDocumentation)
            {
                <tr>
                    <td class="parameter-name"><b>@propInfo.Name</b> (@propInfo.Type)</td>

                    <td class="parameter-documentation">
                        <pre>@propInfo.Documentation</pre>
                    </td>
                </tr>
            }
        </tbody>
    </table>
}

这篇关于的ASP.NET Web API生成模型的所有参数 - 帮助页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆