ASP.NET Web API 2:创建API帮助页面
当你新建了一个web API服务之后,再建一个API帮助页面是很有好处的,这样其他开发人员就会很清楚地知道如何调用你的API接口。你可以选择自己手工建立,但是如果能自动生成岂不是更好。为了简化这项任务, ASP.NET Web API提供了一个在运行时自动生成帮助页的库。




在项目中添加帮助页,首先使用NuGet安装Microsoft.AspNet.WebApi.HelpPage库

安装成功后,启动项目有可能会报下图的异常


引起异常的原因是Microsoft.AspNet.WebApi.HelpPage库要依赖于如下程序集,如果项目中使用的程序集版本低于它依赖的版本,NuGet就会把这些程序集升级到依赖的版本。升级之后引起了本地程序集和GAC的程序集冲突。

解决该问题的办法是,在项目的Web.config配置文件中的runtime节点,添加:
< dependentAssembly>
< assemblyIdentity name = "System.Web.WebPages.Razor " publicKeyToken =" 31bf3856ad364e35 "/>
< bindingRedirect oldVersion = "1.0.0.0-3.0.0.0 " newVersion =" 3.0.0.0 "/>
</ dependentAssembly >
在项目Areas 文件夹下就自动生成了有关帮助页的所有代码文件

启动项目,帮助页的相对路径是/Help,如果你新增加了API控制器,帮助页内容会在运行时自动更新。

帮助页对应的MVC视图在项目中的路径是Areas/HelpPage/Views/Help/Index.cshtml,你可以随自己的意愿定制该视图的布局、介绍、标题、样式等等。
默认生成的帮助页有很多没什么实际意义的占位字符串。

你可以使用XML文档注释功能来创建有意义的文档。要开启该功能,需要打开Areas/HelpPage/App_Start/HelpPageConfig.cs文件,取消下面这句代码的注释:
// Uncomment the following to use the documentation from XML documentation file.
config.SetDocumentationProvider( new XmlDocumentationProvider ( HttpContext.Current.Server.MapPath( "~/App_Data/XmlDocument.xml" )));
然后在解决方案资源管理器,右键项目名称,选择属性,选择生成,在输出配置项,勾选XML文档文件,修改输出路径为App_Data/XmlDocument.xml

然后打开API控制器文件,通过XML文档注释方式(///方式)给控制器的Action方法添加注释

/// <summary>
/// 查询指定ID的商品信息
/// </summary>
/// <param name="id"> 商品ID </param>
/// <returns> 查询到的商品记录 </returns>
[ HttpGet]
public Product Get( int id)
{
return repository.Products.FirstOrDefault(p => p.ProductId == id);
}

重新编译运行项目,导航到帮助页,添加的注释信息就显示到了帮助页

如果要帮助页上隐藏某个API接口的信息,可以给该Action添加ApiExplorerSettings特性同时IgnoreApi属性设置为true

/// <summary>
/// 获取商品列表
/// </summary>
/// <returns> 商品列表 </returns>
[ ApiExplorerSettings(IgnoreApi = true )]
public IEnumerable < Product> Get()
{
return repository.Products;
}


你也可以给控制器添加该特性,整个控制器的信息都不会出现在帮助页上。