前言
創建Web API時,創建幫助頁面通常很有用,以便其他開發人員知道如何呼叫您的API,您可以手動創建所有檔案,但是最好自動生成,為了簡化此任務,ASP.NET Web API提供了一個庫,用于在運行時自動生成幫助頁面,
Web API有一個Help Page插件,可以很方便的根據代碼及注釋自動生成相關API說明頁面,
實作
1、右鍵點擊WebAPI專案的參考,選擇"管理NuGet程式包"
在搜索框中輸入 helppage進行搜索,結果如下圖:

2、然后在右側邊欄點擊安裝按鈕即可進行插件安裝了,
安裝完成后,你會發現專案下多了不少檔案:


3、增加MultiXmlDocumentationProvider 檔案
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")));}}
4、重寫HelpPageConfig

5、然后你會發現一切都是英文,那么怎么顯示中文說明呢
首先 選中專案,右鍵-屬性-生成 選擇下面的XML檔案檔案,目錄填寫如下圖所示


6、下一步安裝TestAPI的插件,這個插件會在頁面生成一個按鈕,點擊這個按鈕可以直接除錯WEBAPI 方便到爆炸,
打開Nuget包管理器的控制臺 輸入 Install-Package WebApiTestClient 按成安裝后多了這兩個檔案


大功告成

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/227006.html
標籤:.NET技术
上一篇:windbg 分析cpu例外
