本项目实现了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. Eclipse中项目红叉但找不到错误解决方法

    首先windows-show view-problems 根据地址查找错误 若提示: Description    Resource    Path    Location    TypeJava c ...

  2. python gui之tkinter界面设计pythonic设计

    ui的设计,控件id的记录是一件比较繁琐的事情. 此外,赋值和读取数据也比较繁琐,非常不pythonic. 有没有神马办法优雅一点呢?life is short. 鉴于控件有name属性,通过dir( ...

  3. 基于用户相似性的协同过滤——Python实现

    代码基本来自项亮的<推荐系统实践>,把书上的伪代码具体实现,还参考了https://www.douban.com/note/336280497/ 还可以加入对用户相似性的归一化操作,效果会 ...

  4. c# Dictionary的遍历和排序

    c# Dictionary的遍历和排序 c#遍历的两种方式 for和foreach for: 需要指定首位数据.末尾数据.数据长度: for遍历语句中可以改变数据的值: 遍历规则可以自定义,灵活性较高 ...

  5. iOS NSObject 的 isa 属性的类型 Class

    以前对NSObject的isa属性也知道点,但是了解不深,今天看了这篇博文,感觉很好,总结一下: http://chun.tips/blog/2014/11/05/bao-gen-wen-di-obj ...

  6. Tomcat内存溢出(java.lang.OutOfMemoryError: PermGen space)

    Tomcat启动时报如下错误:     java.lang.OutOfMemoryError: PermGen space 解决办法:     配置相关内存大小.其中按照启动tomcat的不同方式,分 ...

  7. PHP javascript cookie

    2015-07-30 16:54:58 ................................cao!!!! 汉字, 邮箱的@符号 容易出错 PHP setcookie 的时候, 不要url ...

  8. perl运行其他程序的5种方法

    1.使用system函数 运行成功,返回0,运行失败则返回非负整数 system("cmd"); 2.使用qx my $cmd1=qx/date/; 3.使用`` 与qx等效 4. ...

  9. 使用json格式输出

    /** * json输出 * * @param unknown_type $info */ public function json_out ($info) { header('Content-typ ...

  10. vector在C++中的基本用法

    在写BlackJackGame的时候,考虑到要用到容器,所以就对容器的相关知识强化了一下: 因为我想的是有card类,最后要实现发牌,洗牌等等一系列的操作的时候,使用指向card类的对象的指针,将ca ...