NancyFx 2.0的開源框架的使用-CustomModule(自定義模塊)

NancyFx框架的自定義模塊html

新建一個空的Web項目網絡

 

而後經過NuGet庫安裝下面的包app

  • Nancy
  • Nancy.Hosting.Aspnet

而後添加Models,Module,Views三個文件夾,並在Models文件裏面添加NancyRouteAttribute類框架

        //路由的方法
        public string Method { get; set; }
        //路由的路徑
        public string Path { get; set; }
        public NancyRouteAttribute(string method,string path)
        {
            this.Method = method;
            this.Path = path;
        }

而後在Module文件夾添加UglifiedNancyModule類ide

        //使用的自定義 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<Route> 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<Route> GetRoutes()
        {
            var routes = new List<Route>();
            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 Func<NancyContext, bool> GetFilter(string routeMethodName)
        {
            var type = this.GetType();
            var method = type.GetMethod(routeMethodName+"Filter",BindingFlags.Public|BindingFlags.Instance);
            if (method==null)
            {
                return null;
            }
            return (Func<NancyContext,bool>)Delegate.CreateDelegate(typeof(Func<NancyContext,bool>,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;
             };
        }

繼續在Module文件夾添加MainModule類this

        [NancyRoute("GET", "/")]
        public dynamic Root(dynamic parameters)
        {
            return View["Index", new { Name = "Lexan!" }];
        }

        public bool FilteredFilter(NancyContext context)
        {
            return false;
        }

        [NancyRoute("GET", "/filtered")]
        public dynamic Filtered(dynamic parameters)
        {
            return "篩選";
        }

 而後往根目錄添加Bootstrapper類spa

  public override void Configure(INancyEnvironment environment)
        {
            //base.Configure(environment);
            environment.Diagnostics(enabled:true,password:"password");
        }

繼續往根目錄添加SharedAssemblyInfo類code

using System.Runtime.InteropServices;
using System.Reflection;

[assembly:AssemblyInformationalVersion("2.0.0-alpha")]

繼續往Views文件夾裏面添加index.htmlorm

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>你好!</title>
</head>
<body>
    <h1>你好 @Model.Name   這是使用自定義模塊類型實現的</h1>
</body>
</html>

而後看看運行結果htm

謝謝欣賞!

相關文章
相關標籤/搜索