建立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 按成安裝後多了這兩個文件
大功告成