weiapi2.2 HelpPage自动生成接口说明文档和接口测试功能

在开发Webapi项目时每写完一个方法时,是不是需要添加相应的功能说明和测试案例呢?为了更简单方便的写说明接口文档和接口测试HelpPage提供了一个方便的途径。

她的大致原理是:在编译时会生成.dll程序集和.xml程序集说明文件,通过xml文件获取Controller名称、action名称、参数信息和备注信息等。这样接口说明文档就可以放到备注信息了,个人觉得确实粗暴简单 。那接口测试在哪呢?这里用到nuget第三方程序包:webapitestclient

先上效果图吧!

案例是用VS2013创建的,已创建好HelpPage,但wepapi版本是1.0 。wepapi2功能增强,为更上节奏进入nuget升级。

其他的互相依赖项也会升级!

设置xml说明文档路径:

web项目属性设置生成的xml路径:

遗憾webapitestclient只支持最低版本的HelpPage,升级webapi还得修改部分代码!说明:webapi1可以获取action的备注说明但不能获取controller的备注说明 webapi2是可以。

升级后,XmlDocumentationProvider类需要会多出两个实现方法:Controller和action描述方法.

XmlDocumentationProvider.cs 
public class XmlDocumentationProvider : IDocumentationProvider
    {
        private XPathNavigator _documentNavigator;
        private const string TypeExpression = "/doc/members/member[@name=‘T:{0}‘]";
        private const string MethodExpression = "/doc/members/member[@name=‘M:{0}‘]";
        private const string ParameterExpression = "param[@name=‘{0}‘]";

        /// <summary>
        /// Initializes a new instance of the <see cref="XmlDocumentationProvider"/> class.
        /// </summary>
        /// <param name="documentPath">The physical path to XML document.</param>
        public XmlDocumentationProvider(string documentPath="")
        {
            //if (documentPath.IsNullOrWhiteSpace())
            //    documentPath = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["webApiDescription"]);
            if (documentPath == null)
            {
                throw new ArgumentNullException("documentPath");
            }
            XPathDocument xpath = new XPathDocument(documentPath);
            _documentNavigator = xpath.CreateNavigator();
        }
        private XPathNavigator GetTypeNode(Type type)
        {
            string controllerTypeName = GetTypeName(type);
            string selectExpression = String.Format(CultureInfo.InvariantCulture, TypeExpression, controllerTypeName);
            return _documentNavigator.SelectSingleNode(selectExpression);
        }
        private static string GetTagValue(XPathNavigator parentNode, string tagName)
        {
            if (parentNode != null)
            {
                XPathNavigator node = parentNode.SelectSingleNode(tagName);
                if (node != null)
                {
                    return node.Value.Trim();
                }
            }

            return null;
        }
        public virtual string GetDocumentation(HttpControllerDescriptor controllerDescriptor)
        {
            XPathNavigator typeNode = GetTypeNode(controllerDescriptor.ControllerType);
            return GetTagValue(typeNode, "summary");
        }
        public virtual string GetDocumentation(HttpActionDescriptor actionDescriptor)
        {
            XPathNavigator methodNode = GetMethodNode(actionDescriptor);
            if (methodNode != null)
            {
                XPathNavigator summaryNode = methodNode.SelectSingleNode("summary");
                if (summaryNode != null)
                {
                    return summaryNode.Value.Trim();
                }
            }

            return null;
        }

        public virtual string GetDocumentation(HttpParameterDescriptor parameterDescriptor)
        {
            ReflectedHttpParameterDescriptor reflectedParameterDescriptor = parameterDescriptor as ReflectedHttpParameterDescriptor;
            if (reflectedParameterDescriptor != null)
            {
                XPathNavigator methodNode = GetMethodNode(reflectedParameterDescriptor.ActionDescriptor);
                if (methodNode != null)
                {
                    string parameterName = reflectedParameterDescriptor.ParameterInfo.Name;
                    XPathNavigator parameterNode = methodNode.SelectSingleNode(String.Format(CultureInfo.InvariantCulture, ParameterExpression, parameterName));
                    if (parameterNode != null)
                    {
                        return parameterNode.Value.Trim();
                    }
                }
            }

            return null;
        }

        public string GetResponseDocumentation(HttpActionDescriptor actionDescriptor)
        {
            XPathNavigator methodNode = GetMethodNode(actionDescriptor);
            return GetTagValue(methodNode, "returns");
        }

        private XPathNavigator GetMethodNode(HttpActionDescriptor actionDescriptor)
        {
            ReflectedHttpActionDescriptor reflectedActionDescriptor = actionDescriptor as ReflectedHttpActionDescriptor;
            if (reflectedActionDescriptor != null)
            {
                string selectExpression = String.Format(CultureInfo.InvariantCulture, MethodExpression, GetMemberName(reflectedActionDescriptor.MethodInfo));
                return _documentNavigator.SelectSingleNode(selectExpression);
            }

            return null;
        }

        private static string GetMemberName(MethodInfo method)
        {
            string name = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", method.DeclaringType.FullName, method.Name);
            ParameterInfo[] parameters = method.GetParameters();
            if (parameters.Length != 0)
            {
                string[] parameterTypeNames = parameters.Select(param => GetTypeName(param.ParameterType)).ToArray();
                name += String.Format(CultureInfo.InvariantCulture, "({0})", String.Join(",", parameterTypeNames));
            }

            return name;
        }

        private static string GetTypeName(Type type)
        {
            if (type.IsGenericType)
            {
                // Format the generic type name to something like: Generic{System.Int32,System.String}
                Type genericType = type.GetGenericTypeDefinition();
                Type[] genericArguments = type.GetGenericArguments();
                string typeName = genericType.FullName;

                // Trim the generic parameter counts from the name
                typeName = typeName.Substring(0, typeName.IndexOf(‘`‘));
                string[] argumentTypeNames = genericArguments.Select(t => GetTypeName(t)).ToArray();
                return String.Format(CultureInfo.InvariantCulture, "{0}{{{1}}}", typeName, String.Join(",", argumentTypeNames));
            }

            return type.FullName;
        }
    }

修改获取Controller信息:

HelpController.cs

Index.cshtml

ApiGroup.cshtml

public ActionResult Index()
        {
            ViewBag.DocumentationProvider = Configuration.Services.GetDocumentationProvider();
            return View(Configuration.Services.GetApiExplorer().ApiDescriptions);
        }
@model Collection<ApiDescription>

@{
    ViewBag.Title = "ASP.NET Web API Help Page";

    // Group APIs by controller
    ILookup<System.Web.Http.Controllers.HttpControllerDescriptor, ApiDescription> apiGroups = Model.ToLookup(api => api.ActionDescriptor.ControllerDescriptor);
}

<header>
    <div class="content-wrapper">
        <div class="float-left">
            <h1>@ViewBag.Title</h1>
        </div>
    </div>
</header>
<div id="body">
    <section class="featured">
        <div class="content-wrapper">
            <h2>Introduction</h2>
            <p>
                Provide a general description of your APIs here.
            </p>
        </div>
    </section>
    <section class="content-wrapper main-content clear-fix">
        <!--遍历Controller -->
        @foreach (var group in apiGroups)
        {
            @Html.DisplayFor(m => group, "ApiGroup")
        }
    </section>
</div>
@model IGrouping<System.Web.Http.Controllers.HttpControllerDescriptor, ApiDescription>

@{
    var controllerDocumentation = ViewBag.DocumentationProvider != null ?
        ViewBag.DocumentationProvider.GetDocumentation(Model.Key) :
        null;
}
<!--Controller名称 -->
<h2 id="@Model.Key.ControllerName">@Model.Key.ControllerName</h2>
<!--Controller说明备注 -->
@if (!String.IsNullOrEmpty(controllerDocumentation))
{
    <p>@controllerDocumentation</p>
}
<table class="help-page-table">
    <thead>
        <tr><th>API</th><th>Description</th></tr>
    </thead>
    <tbody>
    <!--遍历Action -->
    @foreach (var api in Model)
    {
        <tr>
            <td class="api-name"><a href="@Url.Action("Api", "Help", new { apiId = api.GetFriendlyId() })">@api.HttpMethod.Method @api.RelativePath</a></td>
            <td class="api-documentation">
            @if (api.Documentation != null)
            {
                <p>@api.Documentation</p>
            }
            else
            {
                <p>No documentation available.</p>
            }
            </td>
        </tr>
    }
    </tbody>
</table>

效果如下:

接下来添加接口测试功能.

nuget添加webapitestclient:

进入"获取单个商品信息"接口页面,会多出 "Test Api"按钮,也可以自己修改位置!

点击"Test Api"按钮 弹出调用窗口 :

输入参数调用,输出json数据:

  共享Demo

Webapi2.2WithTest.zip

  作者:HsutonWang

  出处:http://www.cnblogs.com/AntonWang/p/4192119.html/

  本文版权归作者和博客园共有,欢迎转载

时间: 2024-07-30 10:17:05

weiapi2.2 HelpPage自动生成接口说明文档和接口测试功能的相关文章

Swagger(webapi自动生成接口说明文档)

1.引入Swagger.Net.UI和Swashbuckle包 2.卸载重复包Swagger.Net 3.多余的SwaggerUI文件夹 4.项目属性->勾选生成xml文档文件 5.添加类SwaggerCachingProvider和修改SwaggerConfig文件 using Swashbuckle.Swagger; using System; using System.Collections.Concurrent; using System.Collections.Generic; usi

生成项目依赖包文档、自动生成接口文档

一. pipreqs模块生成依赖包文档 项目中通常会安装很多模块,为了移植性更好,我们可以使用pipreqs模块生成依赖包文档. 1.1 安装pipreqs模块 pip install pipreqs 1.2 生成对应项目的路径 切换至项目根目录,或者是给一个项目的路径: D:\youkutest\luffyapi>pipreqs ./ --encoding=utf8 上面项目名为luffyapi,后面加--encoding=utf8是防止因为编码问题报错,建议加上. 1.3 新环境中安装依赖包

自动生成接口文档

自动生成接口文档 REST framework可以自动帮助我们生成接口文档. 接口文档以网页的方式呈现. 自动接口文档能生成的是继承自APIView及其子类的视图. 安装依赖 REST framewrok生成接口文档需要coreapi库的支持. pip install coreapi 设置接口文档访问路径 在总路由中添加接口文档路径. 文档路由对应的视图配置为rest_framework.documentation.include_docs_urls, 参数title为接口文档网站的标题. fr

转:Swagger2自动生成接口文档和Mock模拟数据

转自:https://www.cnblogs.com/vipstone/p/9841716.html 一.简介 在当下这个前后端分离的技术趋势下,前端工程师过度依赖后端工程师的接口和数据,给开发带来了两大问题: 问题一.后端接口查看难:要怎么调用?参数怎么传递?有几个参数?参数都代表什么含义? 问题二.返回数据操作难:数据返回不对或者不够怎么办?怎么才能灵活的操作数据? 这是很多公司前后端分离之后带来的困扰,那怎么来解决这些问题? 问题一的一般解决方案:后端团队共同维护一个在线文档,每次改接口再

Asp Net Core Swagger自动生成接口文档

Swagger是什么 Swagger工具为你的Asp Net Core生成漂亮的API文档.目前社会上大部分都是一个服务端为N个客户端提供接口,往往我们需要提供一个友好的API文档,Swagger的出现,几乎使得API文档完全自动化. 开始使用Swagger 此处我们使用开发IDE为VsCode,输入dotnet new webapi -o SwaggerDemo 创建ASP.NET Core Web API项目 添加Swashbuckle.AspNetCore包(此处不讨论包的安装方法,请自行

powerdesigner逆向自动生成mysql说明文档、PDM

做EDI的项目的时候,用到相关工具powerdesigner,正好我们的一个项目对数据设计阶段时相关文档没有很好的保存下来,查找了一下powderdesigner相关文档,采用逆向工程,从mysql数据库生成pdm数据模型.再配合其它工具生成数据库说明文档 工具/原料 powderdesigner15.0 mysql5.1 pdmreader mysql-connector-odbc-5.1.5-win32.msi 方法/步骤 配置ODBC数据源,安装mysql-connector-odbc-5

Mysql2docx自动生成数据库说明文档

[需要python3.0以上] 首先安装Mysql2docx,如下: pip install Mysql2docx 然后打开pycharm,新建test.py # python from Mysql2docx import Mysql2docx m=Mysql2docx() m.do('127.0.0.1','root','password','db_test',3306) 上面需要注意,当本地数据库可以把ip改成localhost,如果是远程IP,可以改成把IP写成远程IP的! 格式是do(i

esdoc 自动生成接口文档介绍

官网 ESDoc:https://esdoc.org/ JSDoc:http://usejsdoc.org/ 介绍 ESDoc 是一个根据 javascript 文件中注释信息,生成 JavaScript 应用程序或库.模块的 API 文档的工具.具有文档覆盖率统计.系统手册.一体化测试.详细接口说明等特点. ESDoc 与 JSDoc 对比 JSDoc 是目前最火的文档生成工具,它存在的时间也比较长,但是功能上还欠缺一些,比如文档覆盖率.自动测试.搜索等,都没有实现.并且它的使用比较复杂,需要

Swagger自动生成接口文档

<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 htt