nancyfx 自定义路由module

时间:2023-03-09 08:49:07
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错误。 也就是实现了所谓的过滤的功能。

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