ASP.NET Web API帮助页面无法处理通用类型控制器

use*_*380 8 c# asp.net-web-api asp.net-web-api-helppages

我有一个关于ASP.NET Web API HelpPages的问题.

通常,HelpPages可以通过XMLDocumentation示例代码生成WebAPI:

public class ValueControllerBase : ApiController
{
    /// <summary>
    /// Base Do
    /// </summary>
    public IEnumerable<string> Do()
    {
       return new string[] { "value1", "value2" };
    }
}

public class ValuesController : ValueControllerBase
{
    /// <summary>
    /// Testing API
    /// </summary>
    public string Get(int id)
    {
        return "value";
    }
}
Run Code Online (Sandbox Code Playgroud)

这可以成功生成,如下所示:

API
GET api/Values/Get/{id}

Description
Testing API

API
POST api/Values/Do

Description
Base Do
Run Code Online (Sandbox Code Playgroud)

但如果我使用通用基本控制器,它将不会生成API文档.

样品:

public class ValueControllerBase<T> : ApiController
{
    /// <summary>
    /// Base Do
    /// </summary>
    public IEnumerable<string> Do()
    {
        return new string[] { "value1", "value2" };
    }
}

public class ValuesController<String> : ValueControllerBase
{
    /// <summary>
    /// Testing API
    /// </summary>
    public string Get(int id)
    {
        return "value";
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我在第二部分使用代码,HelpPages可以生成API文档,但不生成API注释.我的两个例子之间的区别只是第二部分代码使用泛型类型.

API
GET api/Values/Get/{id}  

Description
Testing API

API
POST api/Values/Do

Description
null
Run Code Online (Sandbox Code Playgroud)

在该方法中Do(),与第一个相比,注释不显示

有没有解决这些问题的解决方案?

Nat*_*n A 12

我能够通过调整一些代码来解决这个问题XmlDocumentationProvider.

最初的实现XmlDocumentationProvider.GetTypeName(Type)如下:

private static string GetTypeName(Type type)
{
    string name = type.FullName;
    if (type.IsGenericType)
    {
        // Format the generic type name to something like: Generic{System.Int32,System.String}
        Type genericType = type.GetGenericTypeDefinition();
        Type[] genericArguments = type.GetGenericArguments();
        string genericTypeName = genericType.FullName;

        // Trim the generic parameter counts from the name
        genericTypeName = genericTypeName.Substring(0, genericTypeName.IndexOf('`'));
        string[] argumentTypeNames = genericArguments.Select(t => GetTypeName(t)).ToArray();
        name = String.Format(CultureInfo.InvariantCulture, "{0}{{{1}}}", genericTypeName, String.Join(",", argumentTypeNames));
    }
    if (type.IsNested)
    {
        // Changing the nested type name from OuterType+InnerType to OuterType.InnerType to match the XML documentation syntax.
        name = name.Replace("+", ".");
    }

    return name;
}
Run Code Online (Sandbox Code Playgroud)

我不知道为什么,但是他们尝试为xml查找创建类型名称以包含实际的泛型属性,而不是泛型类型名称本身(例如,它们创建Nullable {bool}而不是Nullable`1).在xml文件中只定义了通用名称本身.

对代码的简单更改使其能够正确地命名/引用泛型类的文档:

....
if (type.IsGenericType)
{
    Type genericType = type.GetGenericTypeDefinition();
    name = genericType.FullName;
}
....
Run Code Online (Sandbox Code Playgroud)

在进行了更改之后,注释开始正确地显示为泛型类型,对我来说,这也没有破坏其他任何东西.