我对 ASP.NET Web API 帮助页面有疑问。
通常 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";
}
}
这样就可以生成成功了,像这样:
API
GET api/Values/Get/{id}
Description
Testing API
API
POST api/Values/Do
Description
Base Do
但如果我使用通用基础 Controller ,它不会生成 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";
}
}
如果我使用第二部分的代码,HelpPages 可以生成 API 文档,但不会生成 API 注释。我的两个示例之间的区别只是第二部分代码使用了泛型类型。
API
GET api/Values/Get/{id}
Description
Testing API
API
POST api/Values/Do
Description
null
在方法Do()
中,注释与第一个相比没有显示
有什么办法可以解决这些问题吗?
最佳答案
我能够通过调整 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;
}
我不知道为什么,但他们试图为 xml 查找创建类型名称以包含实际的通用属性,而不是通用类型名称本身(例如,他们创建 Nullable{bool} 而不是 Nullable` 1).只有通用名称本身在 xml 文件中定义。
对代码进行简单更改即可使其正确命名/引用泛型类的文档:
....
if (type.IsGenericType)
{
Type genericType = type.GetGenericTypeDefinition();
name = genericType.FullName;
}
....
进行该更改后,泛型类型的注释开始正确显示,对我来说,这也没有破坏任何其他内容。
关于c# - ASP.NET Web API 帮助页面无法处理通用类型 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24350040/