建立Web API时,建立帮助页面一般颇有用,以便其余开发人员知道如何调用您的API。您能够手动建立全部文档,可是最好自动生成。为了简化此任务,ASP.NET Web API提供了一个库,用于在运行时自动生成帮助页面。javascript
Web API有一个Help Page插件,能够很方便的根据代码及注释自动生成相关API说明页面。css
一、右键点击WebAPI项目的引用,选择"管理NuGet程序包"java
在搜索框中输入 helppage进行搜索,结果以下图:sql
二、而后在右侧边栏点击安装按钮便可进行插件安装了。typescript
安装完成后,你会发现项目下多了很多文件:json
三、增长MultiXmlDocumentationProvider 文件ide
using System;using System.Collections.Generic;using System.Linq;using System.Reflection;using System.Web;using System.Web.Http.Controllers;using System.Web.Http.Description;using WebApplication41.Areas.HelpPage.ModelDescriptions;namespace WebApplication41.Areas.HelpPage{public class MultiXmlDocumentationProvider : IDocumentationProvider, IModelDocumentationProvider{private readonly XmlDocumentationProvider[] Providers;public MultiXmlDocumentationProvider(params string[] paths){this.Providers = paths.Select(p => new XmlDocumentationProvider(p)).ToArray();}public string GetDocumentation(MemberInfo subject){return this.GetFirstMatch(p => p.GetDocumentation(subject));}public string GetDocumentation(Type subject){return this.GetFirstMatch(p => p.GetDocumentation(subject));}public string GetDocumentation(HttpControllerDescriptor subject){return this.GetFirstMatch(p => p.GetDocumentation(subject));}public string GetDocumentation(HttpActionDescriptor subject){return this.GetFirstMatch(p => p.GetDocumentation(subject));}public string GetDocumentation(HttpParameterDescriptor subject){return this.GetFirstMatch(p => p.GetDocumentation(subject));}public string GetResponseDocumentation(HttpActionDescriptor subject){return this.GetFirstMatch(p => p.GetDocumentation(subject));}private string GetFirstMatch(Func<XmlDocumentationProvider, string> expr){return this.Providers.Select(expr).FirstOrDefault(p => !String.IsNullOrWhiteSpace(p));}}}
public static class HelpPageConfig{[SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters",MessageId = "WebApplication2.Areas.HelpPage.TextSample.#ctor(System.String)",Justification = "End users may choose to merge this string with existing localized resources.")][SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly",MessageId = "bsonspec",Justification = "Part of a URI.")]public static void Register(HttpConfiguration config){config.SetDocumentationProvider(new MultiXmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/bin/WebApplication41.XML")));}}
四、重写HelpPageConfigui
五、而后你会发现一切都是英文,那么怎么显示中文说明呢this
首先 选中项目,右键-属性-生成 选择下面的XML文档文件,目录填写以下图所示spa
六、下一步安装TestAPI的插件,这个插件会在页面生成一个按钮,点击这个按钮能够直接调试WEBAPI 方便到爆炸。
打开Nuget包管理器的控制台 输入 Install-Package WebApiTestClient 按成安装后多了这两个文件
大功告成