Пример #1
0
        private void RouteRequest(HttpListenerContext context)
        {
            Console.WriteLine($"Request received from '{context.Request.RemoteEndPoint}'.");

            var path = context.Request.Url.AbsolutePath;

            if (path.StartsWith(RootPath))
            {
                path = path.Substring(RootPath.Length);
            }

            try {
                HttpHandlerResult result;
                if (Routes.TryFind(path, out RouteEvent routeAction))
                {
                    try {
                        result = routeAction.Invoke(context);
                    }
                    catch (Exception error) {
                        result = HttpHandlerResult.Exception(error);
                    }
                }
                else
                {
                    result = HttpHandlerResult.NotFound()
                             .SetText($"No handler found matching path '{path}'!");
                }

                result.Apply(context);
            }
            finally {
                try {
                    context.Response.Close();
                }
                catch {}
            }
        }
Пример #2
0
        public void Scan(Assembly assembly)
        {
            var typeList = assembly.DefinedTypes
                           .Where(t => t.IsClass && !t.IsAbstract);

            foreach (var classType in typeList)
            {
                var attr = classType.GetCustomAttribute <HttpHandlerAttribute>();
                if (attr == null)
                {
                    continue;
                }

                RouteList[attr.Path] = (context) => {
                    var handler = Activator.CreateInstance(classType) as HttpHandler;
                    if (handler == null)
                    {
                        throw new ApplicationException($"Unable to construct HttpHandler implementation '{classType.Name}'!");
                    }

                    HttpHandlerResult result = null;
                    switch (context.Request.HttpMethod.ToUpper())
                    {
                    case "GET":
                        result = handler.Get(context);
                        break;

                    case "POST":
                        result = handler.Post(context);
                        break;
                    }

                    return(result);
                };
            }
        }
Пример #3
0
 public HttpHandlerResult NotFound()
 {
     return(HttpHandlerResult.NotFound());
 }
Пример #4
0
 public HttpHandlerResult ExternalView(string name, object param)
 {
     return(HttpHandlerResult.ExternalView(name, param));
 }
Пример #5
0
 public HttpHandlerResult Ok()
 {
     return(HttpHandlerResult.Ok());
 }