コード例 #1
0
        // ReSharper disable once UnusedMember.Global
        public async Task Invoke(System.Collections.Generic.IDictionary <string, object> environment)
#endif
        {
#if OWIN
            var context = new Microsoft.Owin.OwinContext(environment);
#endif

            if (!IsHtmlPageRequest(context) || !IsHangfirePageRequest(context))
            {
#if ASPNETCORE
                await _next.Invoke(context);
#elif OWIN
                await _next.Invoke(environment);
#endif
                return;
            }

            try
            {
                var originalBody = context.Response.Body;

                using (var newBody = new MemoryStream())
                {
                    context.Response.Body = newBody;

#if ASPNETCORE
                    await _next.Invoke(context);
#elif OWIN
                    await _next.Invoke(environment);
#endif

                    context.Response.Body = originalBody;

                    newBody.Seek(0, SeekOrigin.Begin);

                    string newContent;
                    using (var reader = new StreamReader(newBody, Encoding.UTF8, detectEncodingFromByteOrderMarks: true))
                    {
                        newContent = await reader.ReadToEndAsync();
                    }

                    if (_options.DashboardTitle != null)
                    {
                        var newDashboardTitle = _options?.DashboardTitle();
                        if (!string.IsNullOrWhiteSpace(newDashboardTitle))
                        {
                            newContent = _titleRegex.Replace(newContent, newDashboardTitle);
                        }
                    }
                    newContent = _versionningRegex.Replace(newContent, "");
                    newContent = _appNameRegex.Replace(newContent, "NOVAdmin");

                    await context.Response.WriteAsync(newContent);
                }
            }
            catch (Exception ex)
            {
                await context.Response.WriteAsync(ex.ToString());
            }
        }
コード例 #2
0
 public UrlHelper([NotNull] IDictionary <string, object> owinEnvironment)
 {
     if (owinEnvironment == null)
     {
         throw new ArgumentNullException(nameof(owinEnvironment));
     }
     _owinContext = new Microsoft.Owin.OwinContext(owinEnvironment);
 }
コード例 #3
0
        public async Task Invoke(Dictionary <string, object> env)
        {
            var owinCtx = new Microsoft.Owin.OwinContext(env);

            Debug.WriteLine("Incomming..");
            await _next(env);

            Debug.WriteLine("Outgoingin..");
        }
コード例 #4
0
ファイル: ApiModel.cs プロジェクト: findersky/WxSdk
        public Task Invoke(IDictionary<string, object> env)
        {
            Microsoft.Owin.OwinContext ctx = new Microsoft.Owin.OwinContext(env);

            string path = ctx.Request.Uri.AbsolutePath;

            Type t = null;

            if (!apis.TryGetValue(path, out t))
            {
                return _next(env);
            }

            IRequest req = Pioneer.WxSdk.JsonService.FromStream(t, ctx.Request.Body, Encoding.UTF8) as IRequest;

            if (req == null)
            {
                ctx.Response.StatusCode = 400;
                return ctx.Response.WriteAsync("");
            }

            if (SdkConfig.Instance.Deploy != Deploy.Server)
            {
                SdkConfig.Instance.Deploy = Deploy.Server;
            }

            dynamic rsp = null;

            try
            {
                rsp = req.GetResponse();
                rsp.Successed = true;
            }
            catch (WxException we)
            {
                rsp = new System.Dynamic.ExpandoObject();
                rsp.Successed = false;
                rsp.ErrorMessage = we.Message;
                rsp.ErrorCode = we.ErrorCode;
            }
            catch (Exception e)
            {
                rsp = new System.Dynamic.ExpandoObject();
                rsp.Successed = false;
                rsp.ErrorMessage = e.Message;
                rsp.ErrorCode = "";
            }

            string retjson = JsonService.ToJson(rsp);

            ctx.Response.ContentType = "text/json,charset=UTF8";

            return ctx.Response.WriteAsync(retjson);
        }
コード例 #5
0
ファイル: ApiInfoModel.cs プロジェクト: findersky/WxSdk
        public Task Invoke(IDictionary<string, object> env)
        {
            Microsoft.Owin.OwinContext ctx = new Microsoft.Owin.OwinContext(env);

            if (ctx.Request.Uri.AbsolutePath != "/apiinfo")
            {
                return _next(env);
            }

            string retHtml = string.Join("</br>", ApiModel.apis.Keys.ToArray());

            ctx.Response.ContentType = "text/html,charset=UTF8";

            return ctx.Response.WriteAsync(retHtml);
        }
コード例 #6
0
        public bool Authorize(IDictionary<string, object> owinEnvironment)
        {
            var context = new Microsoft.Owin.OwinContext(owinEnvironment);

            // if unknown, assume not local
            if (String.IsNullOrEmpty(context.Request.RemoteIpAddress))
                return false;

            // check if localhost
            if (context.Request.RemoteIpAddress == "127.0.0.1" || context.Request.RemoteIpAddress == "::1")
                return true;

            // compare with local address
            if (context.Request.RemoteIpAddress == context.Request.LocalIpAddress)
                return true;

            return false;
        }
コード例 #7
0
ファイル: Program.cs プロジェクト: panesofglass/fracture.http
        static void Main(string[] args)
        {
            System.AppDomain.CurrentDomain.UnhandledException += Debug;

            var server = new HttpServer(env =>
            {
                var context = new Microsoft.Owin.OwinContext(env);
                var response = context.Response;
                response.StatusCode = 200;
                response.Headers.Add("Content-Type", new[] { "text/plain" });
                response.Headers.Add("Content-Length", new[] { "13" });
                response.Headers.Add("Server", new[] { "Fracture" });
                response.Write("Hello, world!");

                // Complete the Task.
                return Task.FromResult<object>(null);
            });

            server.Start(6667);
            Console.WriteLine("Running server on port 6667.");
            Console.ReadLine();
            server.Dispose();
        }
コード例 #8
0
        public bool Authorize(IDictionary <string, object> owinEnvironment)
        {
            var context = new Microsoft.Owin.OwinContext(owinEnvironment);

            // if unknown, assume not local
            if (String.IsNullOrEmpty(context.Request.RemoteIpAddress))
            {
                return(false);
            }

            // check if localhost
            if (context.Request.RemoteIpAddress == "127.0.0.1" || context.Request.RemoteIpAddress == "::1")
            {
                return(true);
            }

            // compare with local address
            if (context.Request.RemoteIpAddress == context.Request.LocalIpAddress)
            {
                return(true);
            }

            return(false);
        }
コード例 #9
0
ファイル: UrlHelper.cs プロジェクト: harriyott/Hangfire
 public UrlHelper([NotNull] IDictionary<string, object> owinEnvironment)
 {
     if (owinEnvironment == null) throw new ArgumentNullException(nameof(owinEnvironment));
     _owinContext = new Microsoft.Owin.OwinContext(owinEnvironment);
 }
コード例 #10
0
        private static void CreateManagement(ManagementPagesOptions options = null)
        {
            #region 翻译
            var resourceManager        = Hangfire.Dashboard.Resources.Strings.ResourceManager;
            var resourceManField       = typeof(Hangfire.Dashboard.Resources.Strings).GetField("resourceMan", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
            var customHangfireLanguage = new CustomHangfireLanguage(resourceManager, options.translateFunc, options.culture);
            resourceManField.SetValue(null, customHangfireLanguage /*_customHangfireLanguage*/);
            JobHistoryRenderer.Register(customHangfireLanguage);
            //翻译时间脚本
            var jsPath = Hangfire.Dashboard.DashboardRoutes.Routes.Contains("/js[0-9]+") ? "/js[0-9]+" : "/js[0-9]{3}";
            //DashboardRoutes.Routes.Append(jsPath, new DynamicJsDispatcher());
            DashboardRoutes.Routes.Append(jsPath, new EmbeddedResourceDispatcher("application/javascript", Assembly.GetExecutingAssembly(), $"{typeof(GlobalConfigurationExtension).Namespace}.Content.momentLocale.js"));
            //
            #endregion 翻译
            //Cron最近5次运行时间
            //cron?cron=0+0+0+*+*+%3F+
            DashboardRoutes.Routes.Add("/cron", new CommandDispatcher(async context =>
            {
                var cron = context.Request.GetQuery("cron");
                //var result = CronExpressionDescriptor.ExpressionDescriptor.GetDescription(cron, new Options
                //{
                //    ThrowExceptionOnParseError = false,
                //    Verbose = false,
                //    DayOfWeekStartIndexZero = true,
                //    Locale = (locale ?? "en-US")
                //});
                //var cronDescription = Hangfire.Cron.GetDescription(cron);
                var cronDescription = CronExpressionDescriptor.ExpressionDescriptor.GetDescription(cron);
                var cronSchedule    = Cronos.CronExpression.Parse(cron);
                var example         = cronSchedule.GetOccurrences(System.DateTime.UtcNow, System.DateTime.Now.AddYears(5)).Take(5).ToArray();
                //var cronSchedule = NCrontab.CrontabSchedule.Parse(cron);
                //var example = cronSchedule.GetNextOccurrences(System.DateTime.UtcNow, System.DateTime.Now.AddYears(5)).Take(5).ToArray();
                var str = Newtonsoft.Json.JsonConvert.SerializeObject(new
                {
                    Description = cronDescription,
                    Example     = example
                });
                await context.Response.WriteAsync(str);
                return(true);
            }));
            var pages = options.GetPages();
            #region 任务
            ManagementSidebarMenu.Items.Clear();
            foreach (var pageInfo in pages)
            {
                //添加命令
                //ManagementBasePage.AddCommands(pageInfo.Queue);
                //添加菜单连接
                var path = $"{ManagementPage.UrlRoute}/{pageInfo.Title.ToBase64Url()}";
                ManagementSidebarMenu.Items.Add(p => new MenuItem(pageInfo.Title, path)
                {
                    Active = p.RequestPath.StartsWith(path),
                    Metric = new DashboardMetric(
                        "metrics:count",
                        "Metrics_Count",
                        page => new Metric(pageInfo.Metadatas.Length)
                    {
                        //Style = pageInfo.Metadatas.Length > 0 ? MetricStyle.Info : MetricStyle.Default,
                        //Highlighted = pageInfo.Metadatas.Length > 0
                    })
                });
                ////添加页面
                DashboardRoutes.Routes.AddRazorPage(path, x => new ManagementBasePage(pageInfo.Title, pageInfo.Title, pageInfo.Metadatas));
            }
            #endregion 任务

            //暂停取消功能
            GlobalJobFilters.Filters.Add(new PauseStateAttribute());
            DashboardRoutes.Routes.AddRazorPage(ManagementPage.UrlRoute, x => new ManagementPage());
            //DashboardRoutes.Routes.AddRazorPage("/recurring/addJobs", x => new ManagementPage());

            // can't use the method of Hangfire.Console as it's usage overrides any similar usage here. Thus
            // we have to add our own endpoint to load it and call it from our code. Actually is a lot less work
            //DashboardRoutes.Routes.Add("/jsm", new EmbeddedResourceDispatcher("application/javascript", Assembly.GetExecutingAssembly(), $"{typeof(GlobalConfigurationExtension).Namespace}.Content.management.js"));
            //DashboardRoutes.Routes.Add("/jsm", new CombinedResourceDispatcher("application/javascript", Assembly.GetExecutingAssembly(), $"{typeof(GlobalConfigurationExtension).Namespace}.Content", new[] { "management.js", "cron.js" }));
            DashboardRoutes.Routes.Append(jsPath, new CombinedResourceDispatcher("application/javascript", Assembly.GetExecutingAssembly(), $"{typeof(GlobalConfigurationExtension).Namespace}.Content", new[] { "management.js", "cron.js" }));

            //NavigationMenu.Items.Add(page => new MenuItem(ManagementPage.Title, page.Url.To(ManagementPage.UrlRoute))
            //{
            //    Active = page.RequestPath.StartsWith(ManagementPage.UrlRoute)
            //});

            //执行暂停命令
            DashboardRoutes.Routes.AddBatchCommand("/recurring/pause", (context, jobId) =>
            {
                if (context.IsReadOnly)
                {
                    return;
                }
                using (var connection = context.Storage.GetConnection())
                {
                    connection.SetPauseState(jobId, true);
                }
            });
            //执行恢复命令
            DashboardRoutes.Routes.AddBatchCommand("/recurring/repeat", (context, jobId) =>
            {
                if (context.IsReadOnly)
                {
                    return;
                }
                using (var connection = context.Storage.GetConnection())
                {
                    connection.SetPauseState(jobId, false);
                }
            });
            //执行添加任务
            DashboardRoutes.Routes.AddCommand($"{ManagementPage.UrlRoute}/addJob", context =>
            {
                if (context.IsReadOnly)
                {
                    return(false);
                }
                if (context.Request.Method == "POST")
                {
                    //Hangfire官方在Owin模式获取参数会有问题,只能获取一次,第二次会是空值
                    var getFormValue = new Func <string, IList <string> >(key =>
                    {
                        ////Owin模式
                        //var environment = context.GetOwinEnvironment();
                        //var _context = new Microsoft.Owin.OwinContext(environment);
                        //var form = _context.Request.ReadFormSafeAsync().Result;
                        //var r =  form.GetValues(_key);
                        ////aspnet模式
                        //var r = context.Request.GetFormValuesAsync(key)?.Result;
                        //return r.Select(f => string.IsNullOrWhiteSpace(f) ? null : f).ToArray();
                        //通用模式
                        IList <string> getValue(string _key)
                        {
#if NETFULL
                            //Owin模式
                            var environment = context.GetOwinEnvironment();
                            var _context    = new Microsoft.Owin.OwinContext(environment);
                            var form        = _context.Request?.ReadFormAsync()?.Result;
                            return(form?.GetValues(_key));
#else
                            return(context.Request.GetFormValuesAsync(_key)?.Result);
#endif
                        }
                        var r = getValue(key);
                        return(r.Select(f => string.IsNullOrWhiteSpace(f) ? null : f).ToArray());
                    });

                    var jobtype     = getFormValue("type")?.FirstOrDefault();
                    var id          = getFormValue("id")?.FirstOrDefault();
                    var jobMetadata = pages.SelectMany(f => f.Metadatas.Where(fff => fff.GetId() == id)).FirstOrDefault();
                    var par         = new List <object>();

                    foreach (var parameterInfo in jobMetadata.Parameters)
                    {
                        if (parameterInfo.ParameterType == typeof(Server.PerformContext) || parameterInfo.ParameterType == typeof(IJobCancellationToken))
                        {
                            par.Add(null);
                            continue;
                        }
                        ;

                        var variable = $"{id}_{parameterInfo.Name}";
                        if (parameterInfo.ParameterType == typeof(DateTime))
                        {
                            variable = $"{variable}_datetimepicker";
                        }

                        var t = getFormValue(variable);

                        object item   = null;
                        var formInput = t?.FirstOrDefault();
                        if (parameterInfo.ParameterType == typeof(string) || parameterInfo.ParameterType == typeof(Uri) || parameterInfo.ParameterType.IsEnum)
                        {
                            item = formInput;
                        }
                        else if (parameterInfo.ParameterType == typeof(int))
                        {
                            if (formInput != null)
                            {
                                item = int.Parse(formInput);
                            }
                        }
                        else if (parameterInfo.ParameterType == typeof(DateTime))
                        {
                            item = formInput == null ? DateTime.MinValue : DateTime.Parse(formInput);
                        }
                        else if (parameterInfo.ParameterType == typeof(bool))
                        {
                            item = formInput == "on";
                        }
                        else
                        {
                            throw new NotImplementedException();
                        }

                        par.Add(item);
                    }


                    var job    = new Common.Job(jobMetadata.Type, jobMetadata.MethodInfo, par.ToArray());
                    var client = new BackgroundJobClient(context.Storage);
                    switch (jobtype)
                    {
                    case "CronExpression":
                        {
                            var manager = new RecurringJobManager(context.Storage);
                            try
                            {
                                var queue       = getFormValue($"{id}_sys_queue")?.FirstOrDefault();
                                var timeZone    = getFormValue($"{id}_sys_timeZone")?.FirstOrDefault() ?? "Utc";
                                var displayName = getFormValue($"{id}_sys_displayName")?.FirstOrDefault();

                                var jobQueue       = (queue?.Trim().Replace("-", "_").Replace(" ", "_") ?? jobMetadata.Queue)?.ToLower();
                                var jobTimeZone    = TimeZoneInfo.FindSystemTimeZoneById(timeZone?.Trim()) ?? TimeZoneInfo.Utc;
                                var jobDisplayName = string.IsNullOrWhiteSpace(displayName) ? jobMetadata.DisplayName : displayName;

                                var schedule = getFormValue("schedule")?.FirstOrDefault();
                                var cron     = getFormValue($"{id}_sys_cron")?.FirstOrDefault();

                                if (string.IsNullOrWhiteSpace(schedule ?? cron))
                                {
                                    throw new Exception("请填写 Cron 表达式");
                                }
                                manager.AddOrUpdate(jobDisplayName, job, schedule ?? cron, jobTimeZone, jobQueue);
                            }
                            catch (Exception)
                            {
                                return(false);
                            }
                            return(true);
                            //break;
                        }

                    case "ScheduleDateTime":
                        {
                            var datetime = getFormValue($"{id}_sys_datetime")?.FirstOrDefault();
                            if (string.IsNullOrWhiteSpace(datetime))
                            {
                                //context.Response.StatusCode = 400;
                                ////Hangfire.Dashboard.AspNetCoreDashboardResponse
                                context.Response.WriteAsync("请填写 执行时间 表达式");
                                throw new Exception("请填写 执行时间 表达式");
                            }
                            var jobId = client.Create(job, new States.ScheduledState(DateTime.Parse(datetime).ToUniversalTime()));    //Queue
                            return(jobId != string.Empty);
                            //break;
                        }

                    case "ScheduleTimeSpan":
                        {
                            var schedule = getFormValue("schedule")?.FirstOrDefault();
                            var timeSpan = getFormValue($"{id}_sys_timespan")?.FirstOrDefault();
                            if (string.IsNullOrWhiteSpace(schedule ?? timeSpan))
                            {
                                throw new Exception("请填写 延迟时间 表达式");
                            }
                            var jobId = client.Create(job, new States.ScheduledState(TimeSpan.Parse(schedule ?? timeSpan)));    //Queue
                            return(jobId != string.Empty);
                            //break;
                        }
                    //case "ContinueWith":
                    //    {
                    //        var parentId = getValue("{id}_sys_parentId")?.FirstOrDefault();
                    //        var optionsStr = getValue($"{id}_sys_JobContinuationOptions")?.FirstOrDefault();

                    //        var jobContinuationOptions = JobContinuationOptions.OnlyOnSucceededState;
                    //        Enum.TryParse<JobContinuationOptions>(optionsStr, out jobContinuationOptions);
                    //        var jobId = client.Create(job, new States.AwaitingState(parentId, null, jobContinuationOptions));
                    //        return jobId != string.Empty;
                    //        //break;
                    //    }
                    case "Enqueue":
                    default:
                        {
                            var queue    = getFormValue($"{id}_sys_queue")?.FirstOrDefault();
                            var jobQueue = (queue?.Trim().Replace("-", "_").Replace(" ", "_") ?? jobMetadata.Queue)?.ToLower();
                            var jobId    = client.Create(job, new States.EnqueuedState(jobQueue));
                            return(jobId != string.Empty);
                            //break;
                        }
                        //break;
                    }

                    /*
                     * EnqueuedState
                     * Queue
                     * ScheduledState
                     * AddOrUpdate
                     * DisplayName
                     * TimeZone
                     * Queue
                     * ContinueWith
                     * parentId
                     * jobContinuationOptions
                     */



                    //if (!string.IsNullOrEmpty(schedule))
                    //{
                    //    var minutes = int.Parse(schedule);
                    //    return client.Create(job, new ScheduledState(new TimeSpan(0, 0, minutes, 0))) != string.Empty;
                    //}
                    //else if (!string.IsNullOrEmpty(cron))
                    //{
                    //    var manager = new RecurringJobManager(context.Storage);
                    //    try
                    //    {
                    //        manager.AddOrUpdate(jobMetadata.DisplayName, job, cron, TimeZoneInfo.Utc, queue);
                    //    }
                    //    catch (Exception)
                    //    {
                    //        return false;
                    //    }
                    //    return true;
                    //}
                }
                return(false);
            });
            //替换页面
            if (options.OverrideDefaultHangfirePages)
            {
                var type = Type.GetType("Hangfire.Dashboard.RazorPageDispatcher," + typeof(IGlobalConfiguration).Assembly.FullName);
                if (type != null)
                {
                    object obj        = Activator.CreateInstance(type, new object[] { new Func <System.Text.RegularExpressions.Match, RazorPage>(x => new Hangfire.Dashboard.Management.Pages.RecurringJobsPage()) });
                    var    dispatcher = obj as IDashboardDispatcher;//new RazorPageDispatcher( )
                    Hangfire.Dashboard.DashboardRoutes.Routes.Replace("/recurring", dispatcher);

                    object obj2        = Activator.CreateInstance(type, new object[] { new Func <System.Text.RegularExpressions.Match, RazorPage>(x => new Hangfire.Dashboard.Management.Pages.JobDetailsPage(x.Groups["JobId"].Value)) });
                    var    dispatcher2 = obj2 as IDashboardDispatcher;//new RazorPageDispatcher( )
                    Hangfire.Dashboard.DashboardRoutes.Routes.Replace("/jobs/details/(?<JobId>.+)", dispatcher2);

                    object obj3        = Activator.CreateInstance(type, new object[] { new Func <System.Text.RegularExpressions.Match, RazorPage>(x => new Hangfire.Dashboard.Management.Pages.RetriesPage()) });
                    var    dispatcher3 = obj3 as IDashboardDispatcher;//new RazorPageDispatcher( )
                    Hangfire.Dashboard.DashboardRoutes.Routes.Replace("/retries", dispatcher3);

                    object obj4        = Activator.CreateInstance(type, new object[] { new Func <System.Text.RegularExpressions.Match, RazorPage>(x => new Hangfire.Dashboard.Management.Pages.SucceededJobs()) });
                    var    dispatcher4 = obj4 as IDashboardDispatcher;//new RazorPageDispatcher( )
                    Hangfire.Dashboard.DashboardRoutes.Routes.Replace("/jobs/succeeded", dispatcher4);
                }
            }
        }
コード例 #11
0
        /// <summary>
        /// Processa a requisição.
        /// </summary>
        /// <returns></returns>
        public async override Task <object> Handle()
        {
            var context     = new Microsoft.Owin.OwinContext(Environment);
            var wr          = new HttpWorkerRequestWrapper(context);
            var httpContext = new System.Web.HttpContext(wr);

            httpContext.User            = System.Threading.Thread.CurrentPrincipal;
            httpContext.Request.Browser = new System.Web.HttpBrowserCapabilities()
            {
                Capabilities = new System.Collections.Hashtable()
            };
            System.Web.HttpContext.Current = httpContext;
            System.Web.HttpContextBase httpContextBase = null;
            httpContextBase = new System.Web.HttpContextWrapper(httpContext);
            httpContext.Request.Form.HasKeys();
            HttpContext.Current = new HttpContext(context, httpContextBase.Request, httpContextBase.Response);
            var route = base.GetRoute(httpContextBase);

            context.Response.Headers.Add("Server", new[] {
                "Colosoft 1.0"
            });
            if (_application != null)
            {
                _application.OnBeginRequest(context, EventArgs.Empty);
            }
            if (_application != null)
            {
                _application.OnAuthenticateRequest(context, EventArgs.Empty);
            }
            httpContext.User = System.Threading.Thread.CurrentPrincipal;
            System.Web.Routing.IRouteHandler routeHandler = null;
            if (route != null)
            {
                routeHandler = route.RouteHandler;
                if (routeHandler == null)
                {
                    throw new InvalidOperationException("NoRouteHandler");
                }
            }
            if (route != null && !(routeHandler is System.Web.Routing.StopRoutingHandler))
            {
                var requestContext = new System.Web.Routing.RequestContext(httpContextBase, route);
                var httpHandler    = route.RouteHandler.GetHttpHandler(requestContext);
                if (httpHandler == null)
                {
                    throw new InvalidOperationException(string.Format("NoHttpHandler {0}", routeHandler.GetType()));
                }
                try
                {
                    if (httpHandler is System.Web.IHttpAsyncHandler)
                    {
                        var asyncHandler = (System.Web.IHttpAsyncHandler)httpHandler;
                        await Task.Factory.FromAsync <System.Web.HttpContext>(asyncHandler.BeginProcessRequest, asyncHandler.EndProcessRequest, httpContext, null);
                    }
                    else
                    {
                        httpHandler.ProcessRequest(httpContext);
                    }
                }
                catch (Exception ex)
                {
                    if (!FinishRequest(wr, httpContext, ex))
                    {
                        wr.SendStatus(400, "Bad Request");
                        wr.SendKnownResponseHeader(12, "text/html; charset=utf-8");
                        byte[] data = Encoding.ASCII.GetBytes("<html><body>Bad Request </ br>" + ex.ToString() + "</body></html>");
                        wr.SendResponseFromMemory(data, data.Length);
                        wr.FlushResponse(true);
                    }
                }
                if (httpContextBase.Response.StatusCode == 401)
                {
                    httpContextBase.Response.Redirect(string.Format("/login?returnurl={0}", context.Request.Uri.AbsolutePath));
                }
            }
            else
            {
                var path = this.RequestPath;
                if (System.Web.Hosting.HostingEnvironment.VirtualPathProvider.FileExists(path))
                {
                    var file  = System.Web.Hosting.HostingEnvironment.VirtualPathProvider.GetFile(path);
                    var index = path.LastIndexOf('.');
                    if (index >= 0)
                    {
                        var extension   = path.Substring(index);
                        var contentType = Colosoft.Web.ExtendedHtmlUtility.TranslateContentType(extension);
                        if (!string.IsNullOrEmpty(contentType))
                        {
                            httpContextBase.Response.ContentType = contentType;
                        }
                    }
                    var      cacheControl        = httpContextBase.Request.Headers["Cache-Control"];
                    var      ifModifiedSince     = httpContextBase.Request.Headers["If-Modified-Since"];
                    DateTime ifModifiedSinceDate = DateTime.Now;
                    if (!string.IsNullOrEmpty(ifModifiedSince) && DateTime.TryParseExact(ifModifiedSince, "ddd,' 'dd' 'MMM' 'yyyy' 'HH':'mm':'ss' GMT'", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AssumeUniversal | System.Globalization.DateTimeStyles.AdjustToUniversal, out ifModifiedSinceDate))
                    {
                        if (file is Web.Hosting.IPhysicalFileInfo && ((Web.Hosting.IPhysicalFileInfo)file).LastWriteTimeUtc.ToString("yyyy/MM/dd HH:mm:ss") == ifModifiedSinceDate.ToString("yyyy/MM/dd HH:mm:ss"))
                        {
                            httpContextBase.Response.StatusCode = 304;
                            httpContextBase.Response.Flush();
                            if (_application != null)
                            {
                                _application.OnEndRequest(context, EventArgs.Empty);
                            }
                            return(await Task.FromResult <object>(null));
                        }
                    }
                    httpContextBase.Response.AddHeader("Age", "25000");
                    httpContextBase.Response.AddHeader("Cache-Control", "max-age=10000, public");
                    httpContextBase.Response.AddHeader("Date", string.Format(System.Globalization.CultureInfo.InvariantCulture, HTTP_DATEFORMAT, DateTimeOffset.UtcNow));
                    httpContextBase.Response.AddHeader("Expires", string.Format(System.Globalization.CultureInfo.InvariantCulture, HTTP_DATEFORMAT, DateTimeOffset.UtcNow.AddYears(1)));
                    httpContextBase.Response.AddHeader("Vary", "*");
                    if (file is Web.Hosting.IPhysicalFileInfo)
                    {
                        var physicalFile = (Web.Hosting.IPhysicalFileInfo)file;
                        httpContextBase.Response.AddHeader("Content-Length", physicalFile.ContentLength.ToString());
                        httpContextBase.Response.AddHeader("Last-Modified", string.Format(System.Globalization.CultureInfo.InvariantCulture, HTTP_DATEFORMAT, physicalFile.LastWriteTimeUtc));
                    }
                    httpContextBase.Response.Flush();
                    if (file != null)
                    {
                        System.IO.Stream outstream = httpContextBase.Response.OutputStream;
                        var    read   = 0;
                        byte[] buffer = new byte[81920];
                        using (var inputStream = file.Open())
                        {
                            while ((read = inputStream.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                outstream.Write(buffer, 0, read);
                            }
                        }
                        outstream.Flush();
                    }
                }
                else
                {
                    httpContextBase.Response.StatusCode = 404;
                    var virtualPath = "~/Views/404.html";
                    if (System.Web.Hosting.HostingEnvironment.VirtualPathProvider.FileExists(virtualPath))
                    {
                        var virtualFile = System.Web.Hosting.HostingEnvironment.VirtualPathProvider.GetFile(virtualPath);
                        using (var stream = virtualFile.Open())
                        {
                            var reader = new System.IO.StreamReader(stream, httpContextBase.Response.ContentEncoding);
                            var writer = new System.IO.StreamWriter(httpContextBase.Response.OutputStream, httpContextBase.Response.ContentEncoding);
                            writer.Write(reader.ReadToEnd());
                            writer.Flush();
                        }
                    }
                }
            }
            httpContextBase.Response.Flush();
            if (_application != null)
            {
                _application.OnEndRequest(context, EventArgs.Empty);
            }
            return(Task.FromResult <object>(null));
        }