zoukankan      html  css  js  c++  java
  • nancyfx 自定义路由module

    在源码的Nancy.Demo.CustomModule项目示例中

    查看UglifiedNancyModule.cs文件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    private IEnumerable<Route> GetRoutes()
          {
              // Run through all the methods on the class looking
              // for our attribute. If we were to do this for a real
              // app we'd be checking parameters and return types etc
              // but for simplicity we won't bother here.
              var routes = new List<Route>();
              var type = this.GetType();
     
              var methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public).Where(f => (!f.Name.Contains("_")) && (f.Name != "ToString") && (f.Name != "Equals") && (f.Name != "GetType") && (f.Name != "GetHashCode"));
     
              foreach (var method in methods)
              {
                  var attribute = method.GetCustomAttributes(typeof(NancyRouteAttribute), false).FirstOrDefault() as NancyRouteAttribute;
     
     
                  if (attribute == null)
                  {
                      continue;
                  }
     
                  var routeDelegate = WrapFunc((Func<dynamic, dynamic>)Delegate.CreateDelegate(typeof(Func<dynamic, dynamic>), this, method.Name));
     
                  var filter = this.GetFilter(method.Name);
     
                  var fullPath = String.Concat(this.ModulePath, attribute.Path);
     
                  routes.Add(new Route(attribute.Method.ToUpper(), fullPath, filter, routeDelegate));
              }
     
              return routes.AsReadOnly();
          }

    p:上面的代码中我去除了带有_的方法和自带的tostring gethash等冗余方法。

    上面是获取路由的方法,可以看出获取的流程

    首先  获取当前类(UglifiedNancyModule)的所有方法

    其次  循环每一个方法

    然后 查看方法上是否有自定义的属性,示例中为NancyRouteAttribute

    最后 根据方法名和属性名进行特殊处理

    1
    var filter = this.GetFilter(method.Name);

    例子中 调用 http://localhost:56673/filtered 地址时,先查找是否有 FilteredFilter方法(通过  routeMethodName + "Filter"  获取    )

    如果有该方法,则执行该方法,此处为FilteredFilter, 

    如果FilteredFilter返回true  则继续执行filtered这个路由的方法,

    如果FilteredFilter返回false 则返回一个404错误。 也就是实现了所谓的过滤的功能。

    当然如果真是用的时候,用这种方式来过滤,是很蛋疼的。此为项目的演示代码。

        

  • 相关阅读:
    2015.10.9js(页面坐标)
    2015.8.2js-19(完美运动框架)
    2015.7.12js-11(DOM基础)
    2015.7.7js-07-2(基础)
    2015.7.11js-10(无缝滚动)
    2015.7.10js-07(简单时间)
    2015.7.8js-05(简单日历)
    2015-7.7森林探秘季
    jquery scroll()滚动条事件
    资源(127.0.0.1)处于联机状态,但未对连接尝试做出反应
  • 原文地址:https://www.cnblogs.com/wang2650/p/4938773.html
Copyright © 2011-2022 走看看