Creating Help Pages for ASP.NET Web API -摘自网络
When you create a web API, it is often useful to create a help page, so that other developers will know how to call your API. You could create all of the documentation manually, but it is better to autogenerate as much as possible.
To make this task easier, ASP.NET Web API provides a library for auto-generating help pages at run time.
Creating API Help Pages
Install ASP.NET and Web Tools 2012.2 Update. This update integrates help pages into the Web API project template.
Next, create a new ASP.NET MVC 4 project and select the Web API project template. The project template creates an example API controller named ValuesController
. The template also creates the API help pages. All of the code files for the help page are placed in the Areas folder of the project.
When you run the application, the home page contains a link to the API help page. From the home page, the relative path is /Help.
This link brings you to an API summary page.
The MVC view for this page is defined in Areas/HelpPage/Views/Help/Index.cshtml. You can edit this page to modify the layout, introduction, title, styles, and so forth.
The main part of the page is a table of APIs, grouped by controller. The table entries are generated dynamically, using the IApiExplorer interface. (I'll talk more about this interface later.) If you add a new API controller, the table is automatically updated at run time.
The “API” column lists the HTTP method and relative URI. The “Description” column contains documentation for each API. Initially, the documentation is just placeholder text. In the next section, I'll show you how to add documentation from XML comments.
Each API has a link to a page with mroe detailed information, including example request and response bodies.
Adding Help Pages to an Existing Project
You can add help pages to an existing Web API project by using NuGet Package Manager. This option is useful you start from a different project template than the “Web API” template.
From the Tools menu, select Library Package Manager, and then select Package Manager Console. In the Package Manager Console window, type one of the following commands:
For a C# application: Install-Package Microsoft.AspNet.WebApi.HelpPage
For a Visual Basic application: Install-Package Microsoft.AspNet.WebApi.HelpPage.VB
There are two packages, one for C# and one for Visual Basic. Make sure to use the one that matches your project.
This command installs the necessary assemblies and adds the MVC views for the help pages (located in the Areas/HelpPage folder). You'll need to manually add a link to the Help page. The URI is /Help. To create a link in a razor view, add the following:
@Html.ActionLink("API", "Index", "Help", new { area = "" }, null)
Also, make sure to register areas. In the Global.asax file, add the following code to the Application_Start method, if it is not there already:
protected void Application_Start()
{
// Add this code, if not present.
AreaRegistration.RegisterAllAreas();
// ...
}
Adding API Documentation
By default, the help pages have placeholder strings for documentation. You can use XML documentation comments to create the documentation. To enable this feature, open the file Areas/HelpPage/App_Start/HelpPageConfig.cs and uncomment the following line:
config.SetDocumentationProvider(new XmlDocumentationProvider(
HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml")));
Now enable XML documentation. In Solution Explorer, right-click the project and select Properties. Select the Build page.
Under Output, check XML documentation file. In the edit box, type “App_Data/XmlDocument.xml”.
Next, open the code for the ValuesController
API controller, which is defined in /Controllers/ValuesControler.cs. Add some documentation comments to the controller methods. For example:
/// <summary>
/// Gets some very important data from the server.
/// </summary>
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
/// <summary>
/// Looks up some data by ID.
/// </summary>
/// <param name="id">The ID of the data.</param>
public string Get(int id)
{
return "value";
}
Tip: If you position the caret on the line above the method and type three forward slashes, Visual Studio automatically inserts the XML elements. Then you can fill in the blanks.
Now build and run the application again, and navigate to the help pages. The documentation strings should appear in the API table.
The help page reads the strings from the XML file at run time. (When you deploy the application, make sure to deploy the XML file.)
Under the Hood
The help pages are built on top of the ApiExplorer class, which is part of the Web API framework. The ApiExplorer class provides provides the raw material for creating a help page. For each API, ApiExplorer contains an ApiDescription that describes the API. For this purpose, an "API" is defined as the combination of HTTP method and relative URI. For example, here are some distinct APIs:
- GET /api/Products
- GET /api/Products/{id}
- POST /api/Products
If a controller action supports multiple HTTP methods, the ApiExplorer treats each method as a distinct API.
To hide an API from the ApiExplorer, add the ApiExplorerSettings attribute to the action and set IgnoreApi to true.
[ApiExplorerSettings(IgnoreApi=true)]
public HttpResponseMessage Get(int id) { }
You can also add this attribute to the controller, to exclude the entire controller.
The ApiExplorer class gets documentation strings from the IDocumentationProvider interface. As you saw earlier, the Help Pages library provides an IDocumentationProvider that gets documentation from XML documentation strings. The code is located in /Areas/HelpPage/XmlDocumentationProvider.cs. You can get documentation from another source by writing your own IDocumentationProvider. To wire it up, call the SetDocumentationProvider extension method, defined in HelpPageConfigurationExtensions
ApiExplorer automatically calls into the IDocumentationProvider interface to get documentation strings for each API. It stores them in the Documentation property of the ApiDescription and ApiParameterDescription objects.
Next Steps
You aren't limited to the help pages shown here. In fact, ApiExplorer is not limited to creating help pages. Yao Huang Lin has written some great blog posts to get you thinking out of the box:
相关文章
- ASP.NET WebAPi(selfhost)之文件同步或异步上传
- ASP.NET MVC 实现二级域名
- 学习ASP.NET Core Razor 编程系列五——Asp.Net Core Razor新建模板页面
- Uses for MachineKey in ASP.NET
- 高并发分布式系统中生成全局唯一(订单号)Id js返回上一页并刷新、返回上一页、自动刷新页面 父页面操作嵌套iframe子页面的HTML标签元素 .net判断System.Data.DataRow中是否包含某列 .Net使用system.Security.Cryptography.RNGCryptoServiceProvider类与System.Random类生成随机数
- ASP.NET实现二维码 ASP.Net上传文件 SQL基础语法 C# 动态创建数据库三(MySQL) Net Core 实现谷歌翻译ApI 免费版 C#发布和调试WebService ajax调用WebService实现数据库操作 C# 实体类转json数据过滤掉字段为null的字段
- .net mvc 站点自带简易SSL加密传输 Word报告自动生成(例如 导出数据库结构) 微信小程序:动画(Animation) SignalR 设计理念(一) ASP.NET -- WebForm -- ViewState ASP.NET -- 一般处理程序ashx 常用到的一些js方法,记录一下 CryptoJS与C#AES加解密互转
- [C#]使用 C# 代码实现拓扑排序 dotNet Core WEB程序使用 Nginx反向代理 C#里面获得应用程序的当前路径 关于Nginx设置端口号,在Asp.net 获取不到的,解决办法 .Net程序员 初学Ubuntu ,配置Nignix 夜深了,写了个JQuery的省市区三级级联效果
- MVC的验证(模型注解和非侵入式脚本的结合使用) .Net中初探Redis .net通过代码发送邮件 Log4net (Log for .net) 使用GDI技术创建ASP.NET验证码 Razor模板引擎 (RazorEngine) .Net程序员应该掌握的正则表达式
- ADO.NET .net core2.0添加json文件并转化成类注入控制器使用 简单了解 iTextSharp实现HTML to PDF ASP.NET MVC 中 Autofac依赖注入DI 控制反转IOC 了解一下 C# AutoMapper 了解一下
- C#中的函数式编程:递归与纯函数(二) 学习ASP.NET Core Razor 编程系列四——Asp.Net Core Razor列表模板页面
- .NET版Word处理控件Aspose.Words功能演示:从C#.NET中的模板生成Word文档
- asp.net给文件分配自己主动编号,如【20140710-1】
- 为什么重新设计 ASP.NET?
- Asp.Net MVC学习总结之过滤器详解(转载)
- 通过扩展让ASP.NET Web API支持JSONP -摘自网络
- 解决网站出错后 跳转 友好页面 的 asp .net 配置
- C#-asp.net 每天的某时刻定时执行任务
- ASP.NET quartz 定时任务
- 给ASP.NET Core WebAPI添加Swagger支持