本项目实现了ASP.NET WebApi 接口文档的自动生成功能。

微软出的ASP.NET WebApi Help Page固然好用,但是我们项目基于Owin 平台的纯WebApi 项目,不想引入MVC 的依赖,因此我们需要定制下ASP.NET WebApi Help Page。

首先来个学生习作版本:

var info = typeof(AccountController);
var sb = new StringBuilder();
var methods = info.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
foreach (var m in methods)
{
    sb.AppendLine(m.Name);
    var pi = m.GetParameters();
    //Get Http Method
    var postAtts = m.GetCustomAttributes(typeof(HttpPostAttribute), false);
    if (postAtts.Count() != 0)
    {
        sb.AppendLine("POST");
    }
    else
    {
        sb.AppendLine("GET");
    }
    //Get Route
    var routeAtts = m.GetCustomAttributes(typeof(RouteAttribute), false);
    if (postAtts.Count() != 0)
    {
        var routeTemp = (RouteAttribute)routeAtts[0];
        sb.AppendLine(routeTemp.Template);
    }

    //Get parameter
    foreach (ParameterInfo t in pi)
    {
        var tt = t.ParameterType;

        if (tt == typeof(string))
        {
            sb.AppendLine("Query String : " + t.Name + "={string}");
        }
        else if (tt == typeof(Guid))
        {
            sb.AppendLine("Query String Or URL : " + t.Name + "={guid}");
        }
        else if (tt.BaseType == typeof(Enum))
        {
            sb.AppendLine("Query String : " + t.Name + "={Enum}");
        }
        else if (tt.BaseType == typeof(object))
        {
            var paramter = Activator.CreateInstance(tt);
            var json = JsonHelper.ToJsonString(paramter);
            json = json.Replace("null", "\"string\"");
            sb.AppendLine(json);
        }
    }
    sb.AppendLine();
}

var result = sb.ToString();

这种东西只能写作业的时候随便写写,用到项目中还是差点火候的。我们接下去进入正题。帮助页面必然分为一个Index, 一个Detail。Index 页面需要获取所有的Controller 以及下面的Action。研究了下代码,发现系统以及给我们封装好了对应的方法,直接调用即可。

 [HttpGet]
    [Route("api/Helps")]
    public HttpResponseMessage Index()
    {
        var descriptions = Configuration.Services.GetApiExplorer().ApiDescriptions;
        var groups = descriptions.ToLookup(api => api.ActionDescriptor.ControllerDescriptor);

        StringBuilder html = GetHtmlFromDescriptionGroup(groups);
        var response = this.Request.CreateResponse();
        response.Content = new StringContent(html.ToString(), Encoding.UTF8, "text/HTML");

        return response;
    }

由于是纯API的,返回的HTML就不用什么模板了,直接拼接字符串搞定。

Index 向Detail 跳转,这里有一个有意思的方法:

 public static string GetFriendlyId(this ApiDescription description)
    {
        string path = description.RelativePath;
        string[] urlParts = path.Split('?');
        string localPath = urlParts[0];
        string queryKeyString = null;
        if (urlParts.Length > 1)
        {
            string query = urlParts[1];
            string[] queryKeys = HttpUtility.ParseQueryString(query).AllKeys;
            queryKeyString = String.Join("_", queryKeys);
        }

        StringBuilder friendlyPath = new StringBuilder();
        friendlyPath.AppendFormat("{0}-{1}",
            description.HttpMethod.Method,
            localPath.Replace("/", "-").Replace("{", String.Empty).Replace("}", String.Empty));
        if (queryKeyString != null)
        {
            friendlyPath.AppendFormat("_{0}", queryKeyString.Replace('.', '-'));
        }
        return friendlyPath.ToString();
    }

然后在详情界面里解析出我们需要的参数,以及自动生成sample

      [HttpGet]
    [Route("api/Helps/Detail")]
    public HttpResponseMessage Detail(string apiId)
    {
        var apiModel = Configuration.GetHelpPageApiModel(apiId);
        var html = GetHtmlFromApiModel(apiModel);

        var response = this.Request.CreateResponse();
        response.Content = new StringContent(html.ToString(), Encoding.UTF8, "text/HTML");

        return response;
    }

大概耗时3个hour,最后发现基本上是直接搬运了代码,用StringBuilder 代替了view 部分就完成了我们想要的功能,一种搬砖的感觉油然而生,这样的感觉不好。

ASP.NET WebApi Document Helper的更多相关文章

  1. OData – the best way to REST–实例讲解ASP.NET WebAPI OData (V4) Service & Client

    一.概念介绍 1.1,什么是OData? 还是看OData官网的简单说明: An open protocol to allow the creation and consumption of quer ...

  2. 【开源】分享一个前后端分离方案-前端angularjs+requirejs+dhtmlx 后端asp.net webapi

    一.前言 半年前左右折腾了一个前后端分离的架子,这几天才想起来翻出来分享给大家.关于前后端分离这个话题大家也谈了很久了,希望我这个实践能对大家有点点帮助,演示和源码都贴在后面. 二.技术架构 这两年a ...

  3. Asp.net WebAPI 单元测试

    现在Asp.net webapi 运用的越来越多,其单元而是也越来越重要.一般软件开发都是多层结构,上层调用下层的接口,而各层的实现人员不同,一般大家都只写自己对应单元测试.对下层的依赖我们通过IOC ...

  4. Using ASP.Net WebAPI with Web Forms

    Asp.Net WebAPI is a framework for building RESTful HTTP services which can be used across a wide ran ...

  5. 前端angularjs+requirejs+dhtmlx 后端asp.net webapi

    享一个前后端分离方案源码-前端angularjs+requirejs+dhtmlx 后端asp.net webapi   一.前言 半年前左右折腾了一个前后端分离的架子,这几天才想起来翻出来分享给大家 ...

  6. ASP.NET WebAPI使用Swagger生成测试文档

    ASP.NET WebAPI使用Swagger生成测试文档 SwaggerUI是一个简单的Restful API测试和文档工具.简单.漂亮.易用(官方demo).通过读取JSON配置显示API .项目 ...

  7. ASP.NET WebAPI 测试文档 (Swagger)

    ASP.NET WebAPI使用Swagger生成测试文档 SwaggerUI是一个简单的Restful API测试和文档工具.简单.漂亮.易用(官方demo).通过读取JSON配置显示API .项目 ...

  8. [转]OData – the best way to REST–实例讲解ASP.NET WebAPI OData (V4) Service & Client

    本文转自:http://www.cnblogs.com/bluedoctor/p/4384659.html 一.概念介绍 1.1,什么是OData? 还是看OData官网的简单说明: An open ...

  9. ASP.NET WebApi 中使用swagger 构建在线帮助文档

    1 在Visual Studio 中创建一个Asp.NET  WebApi 项目,项目名:Com.App.SysApi(本例创建的是 .net 4.5 框架程序) 2  打开Nuget 包管理软件,查 ...

随机推荐

  1. 11.7---叠罗汉表演节目(CC150)

    1,牛客网第一题:这其实跟找最长递增子序列是一个东西.注意的地方是,返回的是最大的dp,而不是dp[N-1]. 答案: public static int getHeight(int[] men, i ...

  2. 深度分析Linux下双网卡绑定七种模式 多网卡的7种bond模式原理

    http://blog.csdn.net/abc_ii/article/details/9991845多网卡的7种bond模式原理 Linux网卡绑定mode共有七种(~) bond0.bond1.b ...

  3. 【架构】MQTT/XMPP/GCM 等参考资料

    https://www.zhihu.com/question/29138530 https://segmentfault.com/q/1010000002598843/a-10200000026014 ...

  4. [20160704]Addition program that use JOptionPane for input and output

    //Addition program that use JOptionPane for input and output. import javax.swing.JOptionPane; public ...

  5. css 旋转

    div { transform:rotate(7deg); /*Internet Explorer 10.Firefox.Opera 支持 transform 属性*/ -ms-transform:r ...

  6. poj 1700

    http://poj.org/problem?id=1700 题目大意就是一条船,有N个人需要过河,求N个人最短过河的时间 #include <stdio.h> int main() { ...

  7. 【小姿势】如何搭建ipa下载web服务器(直接在手机打开浏览器安装)

    前提: 1) 有个一个现成的web服务器,我用是nodejs. 2) 有个能在用你手机安装的ipa 3) 有个github账号 开搞: 1.用http://plist.iosdev.top/plist ...

  8. linux下的防火墙iptables

    防火墙(firewall),也称为防护墙,是由Check Point创立者Gil Shwed于1993年发明并引入国际互联网.它是一项信息安全的防护系统,依照特定的规则,允许或者是限制传输的数据通过. ...

  9. PHP带重试功能的curl

    2016年1月13日 10:48:10 星期三 /** * @param string $url 访问链接 * @param string $target 需要重试的标准: 返回结果中是否包含$tar ...

  10. ubuntu下安装mysql

    现在的软件越来越好安装,尤其是在ubuntu下安装软件,更是没有技巧,只需要在联网的情况下使用apt-get inatll 即可.在决定安装mysql之前,要先确定系统是否已经安装mysql.如下图: ...