- //使用的自定义 INancyModule 实现
- //方法的属性(eugh!) 来定义路由。
- //没有人在他们正确的头脑将编写一个网络框架
- //使用属性进行路由的;
- public AfterPipeline After {
- get;
- set;
- }
- public BeforePipeline Before {
- get;
- set;
- }
- public ErrorPipeline OnError {
- get;
- set;
- }
- public NancyContext Context {
- get;
- set;
- }
- public IResponseFormatter Response {
- get;
- set;
- }
- public IModelBinderLocator ModelBinderLocator {
- get;
- set;
- }
- public ModelValidationResult ModelValidationoResult {
- get;
- set;
- }
- public IModelValidatorLocator ValidatorLocator {
- get;
- set;
- }
- public Request Request {
- get;
- set;
- }
- public IViewFactory ViewFactory {
- get;
- set;
- }
- public string ModulePath {
- get;
- set;
- }
- public ViewRenderer View {
- get {
- return new ViewRenderer(this);
- }
- }
- public Negotiator Negotiate {
- get {
- return new Negotiator(this.Context);
- }
- }
- public UglifiedNancyModule() : this(string.Empty) {}
- public IEnumerable Routes {
- get {
- return this.GetRoutes();
- }
- }
- public dynamic Text {
- get;
- set;
- }
- private UglifiedNancyModule(string modulePath) {
- this.After = new AfterPipeline();
- this.Before = new BeforePipeline();
- this.OnError = new ErrorPipeline();
- this.ModulePath = modulePath;
- }
- //在类上运行所有方法
- //为我们的属性。如果我们是为了一个真实的
- //我们将检查参数和返回类型等
- private IEnumerable GetRoutes() {
- var routes = new List();
- var type = this.GetType();
- var methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public);
- 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 < object > (attribute.Method.ToUpper(), fullPath, filter, routeDelegate));
- }
- return routes.AsReadOnly();
- }
- //在返回任务的委托中包装同步委托
- private Funcbool > GetFilter(string routeMethodName) {
- var type = this.GetType();
- var method = type.GetMethod(routeMethodName + "Filter", BindingFlags.Public | BindingFlags.Instance);
- if (method == null) {
- return null;
- }
- return (Funcbool > ) Delegate.CreateDelegate(typeof(Funcbool > , this, method.Name));
- }
- private static Func < dynamic,
- CancellationToken,
- Task < dynamic >> WrapFunc(Func < object, object > syncFunc) {
- return (p, ct) = >{
- var tcs = new TaskCompletionSource < dynamic > ();
- try {
- var result = syncFunc.Invoke(p);
- tcs.SetResult(result);
- } catch(Exception e) {
- tcs.SetException(e);
- //throw;
- }
- return tcs.Task;
- };
- }
来源: http://www.cnblogs.com/R00R/p/6870229.html