First, why to generate a description document
As we all know, the API we write for others to call, it is necessary to use text to call methods and considerations, such as a document to better display our design ideas and ideas, so that callers more efficient use of our API.
Of course, you can hand-write your documents without any tools, and then make them into CHM or HTML to the customer, which is a little inefficient and requires manual changes to the documentation after the API changes.
Is there a convenient way to update the documentation automatically when the API changes? The answer is yes.
Second, the specific implementation of the automatic generation of the description document
We are mainly here to The implementation of the GlobalConfiguration.Configuration.Services description is implemented in a way that implements the Idocumentationprovider interface, and then replaces the implementation by calling the Replace method.
Baidu Search Xmlcommentdocumentationprovider, there are many results oh. These are from Microsoft's official Daniel this article:
Http://blogs.msdn.com/b/yaohuang1/archive/2012/05/21/asp-net-web-api-generating-a-web-api-help-page-using-apiexplorer.aspx
Here is the implementation of Xmlcommentdocumentationprovider:
usingSystem.Linq;usingSystem.Reflection;usingSystem.Text.RegularExpressions;usingSystem.Web.Http;usingSystem.Web.Http.Controllers;usingSystem.Web.Http.Description;usingSYSTEM.WEB.MVC;usingSystem.Xml.XPath;namespacedeepleo.api{/// <summary> ///Xmlcommentdocumentationprovider/// </summary> Public classXmlcommentdocumentationprovider:idocumentationprovider {ReadOnlyXPathNavigator _documentnavigator; Private Const string_methodexpression ="/doc/members/member[@name = ' m:{0} ']"; Private Static ReadOnlyRegex _nullabletypenameregex =NewRegex (@"(.*\. Nullable)"+ Regex.escape ("' 1[[") +"([^,]*),.*"); /// <summary> ///ctor/// </summary> /// <param name= "Documentpath" >Document Path</param> PublicXmlcommentdocumentationprovider (stringdocumentpath) {XPathDocument XPath=NewXPathDocument (documentpath); _documentnavigator=XPath. CreateNavigator (); } Public Virtual stringgetdocumentation (Httpactiondescriptor actiondescriptor) {XPathNavigator membernode=Getmembernode (Actiondescriptor); if(Membernode! =NULL) {XPathNavigator summarynode= Membernode.selectsinglenode ("Summary"); if(Summarynode! =NULL) { returnSummaryNode.Value.Trim (); } } return ""; } Public Virtual stringgetdocumentation (Httpparameterdescriptor parameterdescriptor) {Reflectedhttpparameterdescriptor re Flectedparameterdescriptor= Parameterdescriptor asReflectedhttpparameterdescriptor; if(Reflectedparameterdescriptor! =NULL) {XPathNavigator membernode=Getmembernode (Reflectedparameterdescriptor.actiondescriptor); if(Membernode! =NULL) { stringParameterName =ReflectedParameterDescriptor.ParameterInfo.Name; XPathNavigator Parameternode= Membernode.selectsinglenode (string. Format ("param[@name = ' {0} ']", parametername)); if(Parameternode! =NULL) { returnParameterNode.Value.Trim (); } } } return ""; } PrivateXPathNavigator Getmembernode (Httpactiondescriptor actiondescriptor) {Reflectedhttpactiondescriptor Reflectedactiondescriptor= Actiondescriptor asReflectedhttpactiondescriptor; if(Reflectedactiondescriptor! =NULL) { stringSelectexpression =string. Format (_methodexpression, Getmembername (Reflectedactiondescriptor.methodinfo)); XPathNavigator node=_documentnavigator.selectsinglenode (selectexpression); if(Node! =NULL) { returnnode; } } return NULL; } Private Static stringGetmembername (MethodInfo method) {if(method. DeclaringType = =NULL) return string. Empty; stringName =string. Format ("{0}. {1}", method. Declaringtype.fullname, method. Name); varParameters =method. GetParameters (); if(Parameters. Length! =0) { string[] parametertypenames = parameters. Select (param =processtypename (param. Parametertype.fullname)). ToArray (); Name+=string. Format ("({0})",string. Join (",", Parametertypenames)); } returnname; } Private Static stringProcesstypename (stringtypeName) { //Handle Nullable varresult =_nullabletypenameregex.match (typeName); if(result.) Success) {return string. Format ("{0}{{{1}}}", result. groups[1]. Value, result. groups[2]. Value); } returnTypeName; } }}
View Code
This code is generic, and the direct copy is OK in the past.
This blog Park Daniel Zhang Shanyu Teacher's blog has more detailed description: http://www.cnblogs.com/shanyou/archive/2012/06/02/2532370.html
I'm mainly talking about how the following is achieved:
The first step: you need to open the Generate XML comment file Option in project build, as shown in:
Step two: Transform HomeController.
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingsystem.web;usingSYSTEM.WEB.MVC;usingSystem.Web.Http.Description;usingSystem.Web.Http;namespacemvcapplication1.controllers{ Public classHomecontroller:controller { PublicActionResult Index () {varConfig =globalconfiguration.configuration; Config. Services.replace (typeof(Idocumentationprovider),NewXmlcommentdocumentationprovider (HttpContext.Server.MapPath ("~/bin/mvcapplication1.xml"))); varApiexplorer =CONFIG. Services.getapiexplorer (); returnView (Apiexplorer); } }}
The main idea of the code is to read the XML file and replace the previous implementation with our Xmlcommentdocumentationprovider.
The last step below modifies the view.
@model system.web.http.description.iapiexplorer@{viewbag.title="API Description Documentation";}<div id="Body"> <sectionclass="Featured"> <divclass="Content-wrapper"> class="title"> class="content-wrapper main-content Clear-fix"> <ul>@foreach (varApiinchmodel.apidescriptions) {<li> <p> @api. HttpMethod: <b>@[email protected]</b></p> <blockquote> <b> ;D escription:</b> @api. Documentation<br/>@if (API. Parameterdescriptions.count>0) { <b>Parameters</b> <ul>@foreach (varParameterinchAPI. Parameterdescriptions) {<li> @parameter. Name: @parameter. Documentation {@parameter. Source}</li> } </ul> } </blockquote> </li> } <li> <small> Source: http://www.cnblogs.com/deepleo/p/xmlcommentdocumentationprovider.html</small></li> </ul> </section></div>
Done, online browsing effect: http://weishangapi.deepleo.com
Demo Code Download: Http://files.cnblogs.com/deepleo/WebApplication1.rar
You can see that the comments in your code are automatically displayed in the description document so you can focus on your API design and implementation, and no need to manually change the documentation.
Generate user-friendly documentation for the ASP. NET WEB API