Ejemplo n.º 1
0
        public static HttpRouter MapAttribute(this HttpRouter @this, HandlerCompiler compiler, Func <MethodInfo, IHttpHandler[], IHttpHandler[], IHttpHandler, IHttpHandler> handlerDelegate)
        {
            if (@this == null)
            {
                throw new ArgumentNullException(nameof(@this));
            }
            if (compiler == null)
            {
                throw new ArgumentNullException(nameof(compiler));
            }

            var currentAssembly = typeof(HttpRouterExtensions).Assembly.GetName();
            var assemblies      = AssemblyLoadContext.Default.Assemblies;

            foreach (var assembly in assemblies)
            {
                var referencedAssemblies = assembly.GetReferencedAssemblies();
                foreach (var referencedAssembly in referencedAssemblies)
                {
                    if (AssemblyName.ReferenceMatchesDefinition(currentAssembly, referencedAssembly))
                    {
                        MapAttribute(@this, assembly.GetExportedTypes(), compiler, handlerDelegate);
                        break;
                    }
                }
            }
            return(@this);
        }
Ejemplo n.º 2
0
 public static HttpRouter MapAttribute(this HttpRouter @this, Type[] types, HandlerCompiler compiler)
 {
     return(MapAttribute(@this, types, compiler,
                         (method, typeHandlers, methodHandlers, handler) => {
         var handlers = new List <IHttpHandler>();
         handlers.AddRange(typeHandlers);
         handlers.AddRange(methodHandlers);
         handlers.Add(handler);
         return HttpHandler.CreatePipeline(handlers);
     }));
 }
Ejemplo n.º 3
0
        public static void Register(HandlerCompiler compiler)
        {
            compiler.RegisterParameter((type, parameter, request) => {
                var queryParamsAttribute = parameter.GetCustomAttribute <QueryParamsAttribute>();
                if (queryParamsAttribute == null)
                {
                    return(null);
                }

                //FeaturesExtensions.QueryParams(request).GetValue<T>();
                var queryParams = typeof(FeaturesExtensions).GetMethod("QueryParams", new[] { typeof(HttpRequest) });
                var getValue    = typeof(FeaturesExtensions).GetMethod("GetValue", 1, new[] { typeof(IQueryParams) }).MakeGenericMethod(parameter.ParameterType);
                return(Expression.Call(getValue, Expression.Call(queryParams, request)));
            });
        }
Ejemplo n.º 4
0
        public static void Register(HandlerCompiler compiler)
        {
            compiler.RegisterParameter((type, parameter, request) => {
                var queryAndFormAttribute = parameter.GetCustomAttribute <QueryAndFormAttribute>();
                if (queryAndFormAttribute == null)
                {
                    return(null);
                }

                //FeaturesExtensions.GetValue<QueryAndForm, T>()(new QueryAndForm(FeaturesExtensions.QueryParams(request), FeaturesExtensions.FormParams(request)));
                var handler     = typeof(FeaturesExtensions).GetMethod("GetValue", 2, Type.EmptyTypes).MakeGenericMethod(typeof(QueryAndForm), parameter.ParameterType).Invoke(null, null);
                var queryParams = typeof(FeaturesExtensions).GetMethod("QueryParams", new[] { typeof(HttpRequest) });
                var formParams  = typeof(FeaturesExtensions).GetMethod("FormParams", new[] { typeof(HttpRequest) });
                var ctor        = typeof(QueryAndForm).GetConstructor(new[] { typeof(IQueryParams), typeof(IFormParams) });
                return(Expression.Invoke(Expression.Constant(handler), Expression.New(ctor, Expression.Call(queryParams, request), Expression.Call(formParams, request))));
            });
        }
Ejemplo n.º 5
0
 public static HttpRouter MapAttribute(this HttpRouter @this, Type[] types, HandlerCompiler compiler, Func <MethodInfo, IHttpHandler[], IHttpHandler[], IHttpHandler, IHttpHandler> handlerDelegate)
 {
     if (@this == null)
     {
         throw new ArgumentNullException(nameof(@this));
     }
     if (types == null)
     {
         throw new ArgumentNullException(nameof(types));
     }
     if (compiler == null)
     {
         throw new ArgumentNullException(nameof(compiler));
     }
     if (handlerDelegate == null)
     {
         throw new ArgumentNullException(nameof(handlerDelegate));
     }
Ejemplo n.º 6
0
        public static void Register(HandlerCompiler compiler)
        {
            compiler.RegisterParameter((type, parameter, request) => {
                var queryParamAttribute = parameter.GetCustomAttribute <QueryParamAttribute>();
                if (queryParamAttribute == null)
                {
                    return(null);
                }

                var name = queryParamAttribute.Name ?? parameter.Name;
                //FeaturesExtensions.QueryParams(request).GetValue<T>(name);
                var queryParams = typeof(FeaturesExtensions).GetMethod("QueryParams", new[] { typeof(HttpRequest) });
                var getValue    = typeof(FeaturesExtensions).GetMethod("GetValue", 1, new[] { typeof(IQueryParams), typeof(string) }).MakeGenericMethod(parameter.ParameterType);
                return(Expression.Call(getValue, Expression.Call(queryParams, request), Expression.Constant(name)));
                //TODO
                //TryGetValue()=>parameter.DefaultValue
            });
        }
Ejemplo n.º 7
0
        static void Main(string[] args)
        {
            //Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));

            //Config
            //dynamic config= JsonReader.FromJson5<DynamicObject>(new StreamReader("config.json"));
            //var port = (int)config.Port;
            //var connectionString = (string)config.ConnectionString;

            //XSS
            JsonWriter.RegisterProperty((property, value, writer) => {
                if (property.DeclaringType.Namespace != "WebSample.Models")//only WebSample.Models.class
                {
                    return(null);
                }
                if (property.PropertyType != typeof(string))
                {
                    return(null);
                }
                if (property.IsDefined(typeof(RawStringAttribute)))
                {
                    return(null);
                }
                if (property.DeclaringType.IsDefined(typeof(RawStringAttribute)))
                {
                    return(null);
                }
                //if (value == null) { writer.WriteNull(); } else { writer.WriteString(HtmlEncoder.Default.Encode(value)); }
                var writeNull   = typeof(JsonWriter).GetMethod("WriteNull", Type.EmptyTypes);
                var writeString = typeof(JsonWriter).GetMethod("WriteString", new[] { typeof(string) });
                var encode      = typeof(HtmlEncoder).GetMethod("Encode", new[] { typeof(string) });
                return(Expression.IfThenElse(
                           Expression.Equal(value, Expression.Constant(null)),
                           Expression.Call(writer, writeNull),
                           Expression.Call(writer, writeString, Expression.Call(Expression.Property(null, typeof(HtmlEncoder).GetProperty("Default")), encode, value))
                           ));
            });
            //Exception
            //FeaturesExtensions.UseException((request,response,ex)=> {
            //    //request.Method,request.Version maybe null > be careful
            //    //response.UseRedirect("");
            //    return Task.CompletedTask;
            //});

            //Buffer
            //ConnectionExtensions.Register(Provider<Memory<byte>>.CreateFromProcessor(() => new UnmanagedMemory<byte>(8192).Memory, 2048));
            //StringContent.Register(Provider<Buffer<char>>.CreateFromProcessor(() => Buffer<char>.Create(4096, ArrayPool<char>.Shared, 4096, out var _), 2048, (buff) => buff.Clear());
            //MemoryContent.Register(Provider<Buffer<byte>>.CreateFromProcessor(() => Buffer<byte>.Create(8192, ArrayPool<byte>.Shared, 8192, out var _), 2048, (buff) => buff.Clear());

            var httpSvr = new TcpServer(9999);
            var http    = httpSvr.UseHttp((options, router) => {
                //options.KeepAliveTimeout = 0;
                //options.ReceiveTimeout = 0;
                //options.SendTimeout = 0;

                router.MapFiles("/{*path}", "StaticFiles", null);//null for Test(use maxAge)
                //OR
                //router.MapFile("/favicon.ico", "StaticFiles/favicon.ico", null);
                //router.MapFiles("/Js/{*path}", "StaticFiles/Js/", null);
                //router.MapFiles("/Upload/{*path}", "StaticFiles/Upload/", null);

                var compiler = new HandlerCompiler();
                compiler.Register <SqlDb>(SqlDb.Create <SqliteConnection>("Data Source=data.db", cmd => Debug.WriteLine(cmd.CommandText)));
                compiler.Register <IHttp2Pusher>(req => req.Pusher());
                compiler.Register <Passport>(req => req.GetPassport());

                //if Assembly not load
                //AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(nameof(YourAssemblyName)));
                router.MapAttribute(compiler);//AssemblyLoadContext.Default.Assemblies

                //router.MapSlash();

                Console.WriteLine("GET:");
                foreach (var item in router.GetTree)
                {
                    Console.WriteLine(item.Key);
                }
                Console.WriteLine("POST:");
                foreach (var item in router.PostTree)
                {
                    Console.WriteLine(item.Key);
                }
            }).Use(new SharedModule());

            //Start(int maxConnections, int backlog)
            //Environment.ProcessorCount * 1024, 65535
            //ip,request limit better
            httpSvr.Start();

            var h2Svr = new TcpServer(9899);

            h2Svr.UseHttp2((options) => {
                options.Certificate = new X509Certificate2("server.pfx", "123456");
            }, http.Handler);
            h2Svr.Start();


            Console.WriteLine("http://localhost:9999");
            Console.WriteLine("https://localhost:9899");//Chrome --ignore-certificate-errors
            Console.WriteLine("Login Name: admin");
            Console.WriteLine("Login Password: 123456");
            Console.ReadLine();
        }
Ejemplo n.º 8
0
        public static void Run()
        {
            var compiler = new HandlerCompiler();

            compiler.Register <Object1>(new Object1());//Singleton
            compiler.Register <Object2>(() => new Object2());
            compiler.Register <IHttp2Pusher>(req => req.Pusher());
            compiler.RegisterAsync <AsyncObject>(async(req) =>
            {
                await Task.Delay(1000);
                return(new AsyncObject());
            });
            //泛型
            //Generic
            compiler.Register((type, req) =>
            {
                if (!type.IsGenericType || type.GetGenericTypeDefinition() != typeof(GenericObject <>))
                {
                    return(null);
                }

                var ctor = type.GetConstructor(Type.EmptyTypes);
                return(Expression.New(ctor));
            });

            compiler.RegisterParameterAsync <string>(p => p.Name == "test", async(req) =>
            {
                await Task.CompletedTask;
                return("this is string1");
            });

            compiler.RegisterProperty <string>(p => p.Name == "TestString", _ => "this is string2");

            //compiler.RegisterParameter();
            //compiler.RegisterProperty();

            compiler.RegisterReturn <string>((value, req, resp) =>
            {
                resp.Headers.Add(HttpHeaders.ContentType, "text/plain");
                resp.Content = StringContent.Create(value);
            });
            compiler.RegisterReturnAsync <byte[]>(async(value, req, resp) =>
            {
                await Task.CompletedTask;
                resp.Headers[HttpHeaders.ContentType] = "application/octet-stream";
                resp.Content = MemoryContent.Create(value);
            });


            var h1          = compiler.Compile(typeof(TestService).GetMethod("Test1"));
            var pathParams1 = new PathParams()
            {
                { "pathParam1", "ZhangHe" },
                { "pathParam2", "9999" }
            };
            var req1  = new HttpRequest().PathParams(pathParams1);
            var resp1 = h1.HandleAsync(req1).Result;

            Console.WriteLine();
            Console.WriteLine();
            var h2    = compiler.Compile(typeof(TestService).GetMethod("Test2"));
            var resp2 = h2.HandleAsync(new HttpRequest()).Result;

            Console.WriteLine($"Content:{resp2.Content.ReadStringAsync().Result}");

            Console.WriteLine();
            Console.WriteLine();
            var h3    = compiler.Compile(typeof(TestService).GetMethod("Test3"));
            var resp3 = h3.HandleAsync(new HttpRequest()).Result;

            Console.WriteLine($"Content:{resp3.Content.ReadStringAsync().Result}");

            Console.WriteLine();
            Console.WriteLine();
            var h4    = compiler.Compile(typeof(TestService).GetMethod("Test4"));
            var resp4 = h4.HandleAsync(new HttpRequest()).Result;

            Console.WriteLine($"Content:{resp4.Content.ReadStringAsync().Result}");

            Console.WriteLine();
            Console.WriteLine();
            var h5    = compiler.Compile(typeof(TestService2).GetMethod("Test"));
            var resp5 = h1.HandleAsync(new HttpRequest()).Result;

            foreach (var item in resp5.Headers)
            {
                Console.WriteLine($"{item.Key}={item.Value}");
            }


            //------------------------------------------------------------------------

            var compiler1 = new HandlerCompiler();

            QueryParamAttribute.Register(compiler1);
            QueryParamsAttribute.Register(compiler1);
            QueryAndFormAttribute.Register(compiler1);

            Console.WriteLine();
            Console.WriteLine();
            var h6           = compiler1.Compile(typeof(TestService).GetMethod("Test5"));
            var queryParams6 = new QueryParams()
            {
                { "Name", "ZhangSan" },
                { "Age", "100" }
            };
            var req6  = new HttpRequest().QueryParams(queryParams6);
            var resp6 = h6.HandleAsync(req6).Result;

            Console.WriteLine();
            Console.WriteLine();
            var h7          = compiler1.Compile(typeof(TestService).GetMethod("Test6"));
            var queryParam7 = new QueryParams()
            {
                { "Name", "ZhangSan" }
            };
            var formParams7 = new FormParams()
            {
                { "Age", "100" }
            };
            var req7  = new HttpRequest().QueryParams(queryParam7).FormParams(formParams7);
            var resp7 = h7.HandleAsync(req7).Result;
        }
Ejemplo n.º 9
0
        public static void Run()
        {
            var router = new HttpRouter();

            //var getTree= router.GetTree;
            //var postTree = router.PostTree;
            //var headTree = router.HeadTree;
            //var putTree = router.PutTree;
            //var deleteTree = router.DeleteTree;

            router.MapGet("/get/index", (req, resp) => Console.WriteLine("/get/index"));
            //不支持参数约束,前缀,后缀 繁琐而且用处不大
            //Not support parameter constraints,prefix,suffix tedious and useless
            router.MapGet("/get/{param1}/{param2}", (req, resp) => Console.WriteLine("/get/{param1}/{param2}"));
            router.MapGet("/get/{*catchAll}", (req, resp) => Console.WriteLine("/get/{*catchAll}"));
            Console.WriteLine("MapGet");
            foreach (var item in router.GetTree)
            {
                Console.WriteLine(item.Key);
            }

            //MapAttribute
            var compiler = new HandlerCompiler();//See HandlerCompilerSample

            //compiler.Register()
            router.MapAttribute(new[] { typeof(TestService) }, compiler);
            //customize
            router.MapAttribute(new[] { typeof(TestService) }, compiler,
                                (method, typeHandlers, methodHandlers, handler) =>
            {
                var handlers = new List <IHttpHandler>();
                handlers.Add(HttpHandler.CreateModule((req, handler) =>
                {
                    Console.WriteLine("Before typeHandlers");
                    return(handler.HandleAsync(req));
                }));
                handlers.AddRange(typeHandlers);
                handlers.Add(HttpHandler.CreateModule((req, handler) =>
                {
                    Console.WriteLine("Before methodHandlers");
                    return(handler.HandleAsync(req));
                }));
                handlers.AddRange(methodHandlers);
                handlers.Add(handler);
                return(HttpHandler.CreatePipeline(handlers));
            });
            //router.MapAttribute(compiler);
            //router.MapAttribute(handlerDelegate)
            Console.WriteLine();
            Console.WriteLine("MapAttribute");
            foreach (var item in router.GetTree)
            {
                Console.WriteLine(item.Key);
            }


            Directory.CreateDirectory("Static");
            File.WriteAllText("Static/testFile.txt", "this is file content.BY 张贺", new UTF8Encoding(false));
            File.WriteAllText("Static/testHtml1.html", "<h1>testHtml1<h1>", new UTF8Encoding(false));
            File.WriteAllText("Static/testHtml2.html", "<h2>testHtml2<h2>", new UTF8Encoding(false));
            //MapFile
            router.MapFile("/testFile1", "Static/testFile.txt", 86400);//CacheControl
            router.MapFile("/testFile2", "Static/testFile.txt", "text/html; charset=utf-8", 86400);
            //MapFiles
            router.MapFiles("/static1/{*path}", "Static", 86400);
            var customMimeTypes = new MimeTypes();

            //var customMimeTypes = new MimeTypes(MimeTypes.Default);
            customMimeTypes.Add(".html", "text/html; charset=utf-8");
            router.MapFiles("/static2/{*customName}", "Static", customMimeTypes, 86400, "customName");
            //router.MapFiles("/static2/{*customName}", "Static", MimeTypes.Default, TimeSpan.FromDays(1), "customName");


            //MapSlash
            //尾部/
            router.GetTree.MapSlash();
            //router.MapSlash();
            Console.WriteLine();
            Console.WriteLine("MapSlash");
            foreach (var item in router.GetTree)
            {
                Console.WriteLine(item.Key);
            }

            //动态路由
            //Dynamic change router
            //CopyOnWrite(Safe)
            var newGetTree = new HttpRouter.Tree();

            newGetTree.Map("/new/index", HttpHandler.Create((req, resp) => { Console.WriteLine("/new/index"); }));
            newGetTree.Map("/new/{param1}/{param2}", HttpHandler.Create((req, resp) => { Console.WriteLine("/new/{param1}/{param2}"); }));
            newGetTree.Map("/new/{*catchAll}", HttpHandler.Create((req, resp) => { Console.WriteLine("/new/{*catchAll}"); }));
            newGetTree.MapSlash();
            newGetTree.MapTree(router.GetTree);
            router.GetTree = newGetTree;
            Console.WriteLine();
            Console.WriteLine("NewGetTree");
            foreach (var item in router.GetTree)
            {
                Console.WriteLine(item.Key);
            }

            //Match
            Console.WriteLine();
            Console.WriteLine("Match");
            var params1 = new PathParams();
            var h1      = router.GetTree.Match("/attribute/index", params1);

            Console.WriteLine(params1.Count);
            var params2 = new PathParams();
            var h2      = router.GetTree.Match("/attribute/p1/x/y", params2);

            Console.WriteLine(params2.Count);
            var params3 = new PathParams();
            var h3      = router.GetTree.Match("/attribute/catchAll/x/y/z//", params3);

            Console.WriteLine(params3.Count);

            //HandleAsync
            Console.WriteLine();
            Console.WriteLine("HandleAsync");
            var req1 = new HttpRequest("/attribute/index")
            {
                Method = HttpMethod.Get
            };
            var resp1 = router.HandleAsync(req1).Result;
            var req2  = new HttpRequest("/attribute/p1/x/y")
            {
                Method = HttpMethod.Get
            };
            var resp2 = router.HandleAsync(req2).Result;
            var req3  = new HttpRequest("/attribute/catchAll/x/y/z//")
            {
                Method = HttpMethod.Get
            };
            var resp3 = router.HandleAsync(req3).Result;

            var req4 = new HttpRequest("/testFile1")
            {
                Method = HttpMethod.Get
            };
            var resp4 = router.HandleAsync(req4).Result;

            Console.WriteLine(resp4.Content.ReadStringAsync().Result);
            var req5 = new HttpRequest("/testFile2")
            {
                Method = HttpMethod.Head
            };
            var resp5 = router.HandleAsync(req5).Result;

            Console.WriteLine(resp5.Content.ReadStringAsync().Result);
            var req6 = new HttpRequest("/static1/testHtml1.html")
            {
                Method = HttpMethod.Get
            };
            var resp6 = router.HandleAsync(req6).Result;

            Console.WriteLine(resp6.Content.ReadStringAsync().Result);
            var req7 = new HttpRequest("/static2/testHtml2.html")
            {
                Method = HttpMethod.Get
            };
            var resp7 = router.HandleAsync(req7).Result;

            Console.WriteLine(resp7.Content.ReadStringAsync().Result);


            //------------------------------------------------------------------------
            //router chain(HttpRouter is IHttpHandler)
            var router1 = new HttpRouter();
            var router2 = new HttpRouter();//var tree1 = new HttpRouter.Tree();

            router2.MapGet("/{*path}", (req, resp) => {
                Console.WriteLine(nameof(router2));
                Console.WriteLine(req.PathParams().GetValue <string>("path"));
            });
            router1.GetTree.Map("/Images/{*img}", router2);
            router1.GetTree.Map("/Js/{*js}", HttpHandler.Create(
                                    (req) => {
                Console.WriteLine("Js");
                return(router2.HandleAsync(req));
            }));

            Console.WriteLine();
            var req8 = new HttpRequest("/Images/123456.png")
            {
                Method = HttpMethod.Get
            };
            var resp8 = router1.HandleAsync(req8).Result;
            var req9  = new HttpRequest("/Js/jq.js")
            {
                Method = HttpMethod.Get
            };
            var resp9 = router1.HandleAsync(req9).Result;

            //------------------------------------------------------------------------
            //special
            // /path1/{param1} Match /path1/  (if not Map /path1/)
            var router3 = new HttpRouter();

            router3.MapGet("/", (req, resp) => { Console.WriteLine("/"); });
            router3.MapGet("/{param1}", (req, resp) => { Console.WriteLine("/{param1}"); });
            var req10 = new HttpRequest("/")
            {
                Method = HttpMethod.Get
            };
            var resp10 = router3.HandleAsync(req10).Result;

            var router4 = new HttpRouter();

            //router4.MapGet("/", (req, resp) => { Console.WriteLine("/"); });
            router4.MapGet("/{param1}", (req, resp) => { Console.WriteLine("/{param1}"); });
            var req11 = new HttpRequest("/")
            {
                Method = HttpMethod.Get
            };
            var resp11 = router4.HandleAsync(req11).Result;

            // multiple /
            var router5 = new HttpRouter();

            router5.MapGet("////", (req, resp) => { Console.WriteLine("////"); });
            var req12 = new HttpRequest("////")
            {
                Method = HttpMethod.Get
            };
            var resp12 = router5.HandleAsync(req12).Result;

            router5.MapGet("/Path1/{param1}/{param2}/", (req, resp) => { Console.WriteLine("/Path1/{param1}/{param2}/"); });
            //OR /Path1/{param1}/{param2}/{param3}
            var req13 = new HttpRequest("/Path1///")
            {
                Method = HttpMethod.Get
            };
            var resp13 = router5.HandleAsync(req13).Result;
        }