示例#1
0
        /// <summary>
        /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"/> interface.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests. </param>
        public void ProcessRequest(HttpContext context)
        {
            string appCachePath = context.Server.MapPath("~/application.appcache");

            // response
            HttpResponse response = context.Response;

            response.AddFileDependency(appCachePath);
            foreach (Bundle bundle in BundleTable.Bundles)
            {
                BundleContext bctx = new BundleContext(new HttpContextWrapper(context), BundleTable.Bundles, bundle.Path);
                foreach (BundleFile file in bundle.EnumerateFiles(bctx))
                {
                    string resolvedPath = context.Server.MapPath(file.IncludedVirtualPath);
                    response.AddFileDependency(resolvedPath);
                }
            }

            response.ContentEncoding = Encoding.UTF8;
            response.ContentType     = "text/cache-manifest";
            response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate);
            response.Cache.SetETagFromFileDependencies();
            response.Cache.SetLastModifiedFromFileDependencies();
            response.Cache.VaryByParams.IgnoreParams = true;

            // read each line and transform as required
            using (StreamReader reader = new StreamReader(appCachePath)) {
                string line;

                while ((line = reader.ReadLine()) != null)
                {
                    int   index;
                    Match match;
                    if ((index = line.IndexOf("{version}", StringComparison.OrdinalIgnoreCase)) != -1)
                    {
                        line = line.Substring(0, index) + AppVersion.Informational + line.Substring(index + "{version}".Length);
                    }
                    else if ((line.IndexOf("/bundles", StringComparison.OrdinalIgnoreCase)) != -1)
                    {
                        string bundleAddress = "~" + line;
                        bool   isScript      = line.IndexOf("script", StringComparison.OrdinalIgnoreCase) != -1;
                        line = (isScript ? Scripts.Url(bundleAddress) : Styles.Url(bundleAddress)).ToHtmlString();
                        line = context.Server.HtmlDecode(line);
                    }
                    else if ((match = AppViewDirective.Match(line)).Success)
                    {
                        line = MakeViewUrl(match.Groups["first"].Value);

                        Group secondGroup;
                        if ((secondGroup = match.Groups["second"]) != null && secondGroup.Success)
                        {
                            line += " " + MakeViewUrl(secondGroup.Value);
                        }
                    }

                    context.Response.Write(line);
                    context.Response.Write(Environment.NewLine);
                }
            }
        }
示例#2
0
        private static void OnPreSendRequestHeaders(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;

            // if having a 'version' tag in the query string, add caching headers
            if (!String.IsNullOrEmpty(app.Request.QueryString["v"]))
            {
                HttpResponse response = app.Response;

                var contentType     = response.ContentType;
                var contentEncoding = response.ContentEncoding;
                var status          = response.StatusCode;

                response.ClearHeaders();

                response.StatusCode      = status;
                response.ContentEncoding = contentEncoding;
                response.ContentType     = contentType;

                response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate);
                response.Cache.SetAllowResponseInBrowserHistory(true);

                response.Cache.SetExpires(DateTime.Now.AddYears(1));
                response.Cache.SetMaxAge(new TimeSpan(365, 0, 0, 0));
                response.Cache.SetValidUntilExpires(true);

                if (response.StatusCode == 200 || response.StatusCode == 304)
                {
                    response.AddFileDependency(app.Request.PhysicalPath);

                    response.Cache.VaryByParams["v"] = true;
                    response.Cache.SetETagFromFileDependencies();
                }
            }
        }
示例#3
0
        static void WriteFileToResponse(string fileName, string allowedExtension)
        {
            if (Path.GetExtension(fileName).ToLowerInvariant() != allowedExtension)
            {
                return;
            }
            string       content  = File.ReadAllText(fileName);
            HttpResponse response = HttpUtils.GetResponse();

            response.Write(content);
            response.AddFileDependency(fileName);
        }
示例#4
0
        /// <summary>
        /// 基于文件方式设置客户端缓存
        /// </summary>
        /// <param name="fileName"></param>
        public static void SetFileCaching(string fileName)
        {
            HttpResponse response = GetContext().Response;

            response.AddFileDependency(fileName);
            //基于处理程序文件依赖项的时间戳设置 ETag HTTP 标头。
            response.Cache.SetETagFromFileDependencies();
            //基于处理程序文件依赖项的时间戳设置 Last-Modified HTTP 标头。
            response.Cache.SetLastModifiedFromFileDependencies();
            response.Cache.SetCacheability(HttpCacheability.Public);
            response.Cache.SetMaxAge(new TimeSpan(7, 0, 0, 0));
            response.Cache.SetSlidingExpiration(true);
        }
示例#5
0
        private static void BuildFileItemResponse(HttpContext context, string fileName, long fileSize, DateTime lastModifiedTime, string strETag)
        {
            HttpRequest  request        = context.Request;
            HttpResponse response       = context.Response;
            bool         readIntoMemory = false;
            int          num            = 262144;
            bool         flag2          = false;
            string       str            = request.Headers["Range"];

            if ((str != null) && str.StartsWith("bytes"))
            {
                flag2 = true;
            }

            if (flag2)
            {
                SendEntireEntity(context, strETag, lastModifiedTime);
            }

            if (((fileSize <= num) && !request.RequestType.Equals("(GETSOURCE)")) && !request.RequestType.Equals("(HEADSOURCE)"))
            {
                readIntoMemory = true;
            }

            if (readIntoMemory)
            {
                response.WriteFile(fileName, readIntoMemory);
            }
            else
            {
                response.TransmitFile(fileName);
            }

            response.ContentType = MimeMapping.GetMapping(fileName);
            response.AppendHeader("Accept-Ranges", "bytes");

            if (readIntoMemory)
            {
                response.Cache.AddValidationCallback(new HttpCacheValidateHandler(StaticFileHandler2.CacheValidateHandler), null);
                response.AddFileDependency(fileName);
                //response.Cache.SetExpires(DateTime.Now.AddDays(1));
            }
        }
示例#6
0
        public void HandleImageRequest(HttpResponse Response, string image)
        {
            string path = MediaUtility.GetOriginalFilePath("Banners", image);

            if (path.Length <= 0 || !File.Exists(path))
            {
                Response.StatusCode = 404;
                return;
            }

            string mimeType = @"image";

            if (image.EndsWith(@".jpg", StringComparison.OrdinalIgnoreCase))
            {
                mimeType = @"image/jpg";
            }
            else if (image.EndsWith(@".jpeg", StringComparison.OrdinalIgnoreCase))
            {
                mimeType = @"image/jpeg";
            }
            else if (image.EndsWith(@".png", StringComparison.OrdinalIgnoreCase))
            {
                mimeType = @"image/png";
            }
            else if (image.EndsWith(@".gif", StringComparison.OrdinalIgnoreCase))
            {
                mimeType = @"image/gif";
            }
            else if (image.EndsWith(@".mp4", StringComparison.OrdinalIgnoreCase))
            {
                mimeType = @"video/mp4";
            }
            else if (image.EndsWith(@".mpg", StringComparison.OrdinalIgnoreCase))
            {
                mimeType = @"video/mpeg";
            }

            Response.ContentType = mimeType;
            Response.AddFileDependency(path);
            Response.TransmitFile(path);
        }
        internal static void ProcessRequestInternal(HttpContext context, string pathOverride)
        {
            HttpRequest  request  = context.Request;
            HttpResponse response = context.Response;
            string       virtualPathWithPathInfo;
            string       physicalPath;
            FileInfo     fileInfo;
            long         fileLength;
            DateTime     lastModifiedInUtc;
            string       etag;
            string       rangeHeader;

            // custom virtual path providers that don't yeild a MapPathBasedVirtualFile
            // are a special case, and do not support TransmitFile, WriteFile, Range requests,
            // or the cache policy that we apply below

            /*
             * if (ProcessRequestForNonMapPathBasedVirtualFile(request, response, overrideVirtualPath)) {
             *  return;
             * }
             *
             * if (overrideVirtualPath == null)
             * {
             *  virtualPathWithPathInfo = request.Path;
             *  physicalPath = request.PhysicalPath;
             * }
             * else {
             *  virtualPathWithPathInfo = overrideVirtualPath;
             *  physicalPath = request.MapPath(overrideVirtualPath);
             * }
             */

            if (pathOverride != null)
            {
                physicalPath = pathOverride;
            }
            else
            {
                physicalPath = context.Request.PhysicalPath;
            }

            // Debug.Trace("StaticFileHandler", "Path= " + virtualPathWithPathInfo + ", PhysicalPath= " + physicalPath);

            try
            {
                fileInfo = GetFileInfo(physicalPath);
            }
            catch (HttpException hex)
            {
                int    httpCode  = hex.GetHttpCode();
                string httpError = String.Format("{0} ({1})", hex.Message, physicalPath);
                throw new HttpException(httpCode, httpError, hex);
            }

            // Determine Last Modified Time.  We might need it soon
            // if we encounter a Range: and If-Range header
            // Using UTC time to avoid daylight savings time bug 83230
            lastModifiedInUtc = new DateTime(fileInfo.LastWriteTimeUtc.Year,
                                             fileInfo.LastWriteTimeUtc.Month,
                                             fileInfo.LastWriteTimeUtc.Day,
                                             fileInfo.LastWriteTimeUtc.Hour,
                                             fileInfo.LastWriteTimeUtc.Minute,
                                             fileInfo.LastWriteTimeUtc.Second,
                                             0,
                                             DateTimeKind.Utc);

            // Because we can't set a "Last-Modified" header to any time
            // in the future, check the last modified time and set it to
            // DateTime.Now if it's in the future.
            // This is to fix VSWhidbey #402323
            DateTime utcNow = DateTime.UtcNow;

            if (lastModifiedInUtc > utcNow)
            {
                // use 1 second resolution
                lastModifiedInUtc = new DateTime(utcNow.Ticks - (utcNow.Ticks % TimeSpan.TicksPerSecond), DateTimeKind.Utc);
            }

            etag       = GenerateETag(lastModifiedInUtc, utcNow);
            fileLength = fileInfo.Length;

            // is this a Range request?
            rangeHeader = request.Headers["Range"];
            if (rangeHeader != null && rangeHeader.StartsWith("bytes", StringComparison.OrdinalIgnoreCase) &&
                ProcessRangeRequest(context, physicalPath, fileLength, rangeHeader, etag, lastModifiedInUtc))
            {
                return;
            }

            // if we get this far, we're sending the entire file
            SendFile(physicalPath, 0, fileLength, fileLength, context);

            // Specify content type. Use extension to do the mapping
            response.ContentType = MimeMapping.GetMapping(physicalPath);
            // Static file handler supports byte ranges
            response.AppendHeader("Accept-Ranges", "bytes");
            // We want to flush cache entry when static file has changed
            response.AddFileDependency(physicalPath);

            /*
             * NOTE: This was the code originally in the handler:
             * // Set an expires in the future.
             * response.Cache.SetExpires(utcNow.AddMinutes(5));
             * // always set Last-Modified
             * response.Cache.SetLastModified(lastModifiedInUtc);
             * // always set ETag
             * response.Cache.SetETag(etag);
             * // always set Cache-Control to public
             * response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate);
             */

            // set cache headers
            HttpCachePolicy cachePolicy = response.Cache;

            SetCachingPolicy(cachePolicy);

            // set cache file info
            cachePolicy.SetETag(etag);
            cachePolicy.SetLastModified(lastModifiedInUtc);
        }
 public override void AddFileDependency(string filename)
 {
     _httpResponse.AddFileDependency(filename);
 }
示例#9
0
 public virtual void AddFileDependency(string filename)
 {
     _response.AddFileDependency(filename);
 }
        public void Methods_Deny_Unrestricted()
        {
            HttpResponse response = new HttpResponse(writer);

            response.AddCacheItemDependencies(new ArrayList());
            response.AddCacheItemDependency(String.Empty);
            response.AddFileDependencies(new ArrayList());
            response.AddFileDependency(fname);
#if NET_2_0
            response.AddCacheDependency(new CacheDependency[0]);
            response.AddCacheItemDependencies(new string [0]);
            response.AddFileDependencies(new string [0]);
#endif

            try
            {
                response.AppendCookie(new HttpCookie("mono"));
            }
            catch (NullReferenceException)
            {
                // ms
            }

            try
            {
                Assert.IsNull(response.ApplyAppPathModifier(null), "ApplyAppPathModifier");
            }
            catch (NullReferenceException)
            {
                // ms
            }

            try
            {
                response.Clear();
            }
            catch (NullReferenceException)
            {
                // ms
            }

            try
            {
                response.ClearContent();
            }
            catch (NullReferenceException)
            {
                // ms
            }

            try
            {
                response.ClearHeaders();
            }
            catch (NullReferenceException)
            {
                // ms
            }

            try
            {
                response.Redirect("http://www.mono-project.com");
            }
            catch (NullReferenceException)
            {
                // ms
            }
            try
            {
                response.Redirect("http://www.mono-project.com", false);
            }
            catch (NullReferenceException)
            {
                // ms
            }

            try
            {
                response.SetCookie(new HttpCookie("mono"));
            }
            catch (NullReferenceException)
            {
                // ms
            }

            response.Write(String.Empty);
            response.Write(Char.MinValue);
            response.Write(new char[0], 0, 0);
            response.Write(this);
#if NET_2_0
            response.WriteSubstitution(new HttpResponseSubstitutionCallback(Callback));
#endif

            response.Flush();

            response.Close();

            try
            {
                response.End();
            }
            catch (NullReferenceException)
            {
                // ms
            }
        }
示例#11
0
 public void AddFileDependency(string filename)
 {
     response.AddFileDependency(filename);
 }
示例#12
0
        public void HandleImageRequest(HttpRequest Request, HttpResponse Response, bool IsHead, Int64 AppUserId, string SubFolder)
        {
            Int32 w, h;

            Int32.TryParse(Request.QueryString[@"w"] ?? "", out w);
            Int32.TryParse(Request.QueryString[@"h"] ?? "", out h);

            string image = Request.QueryString[@"image"];

            if (string.IsNullOrEmpty(image))
            {
                Response.StatusCode = 404;
                return;
            }

            string path = null;

            if (w <= 0 && h <= 0)
            {
                path = MediaUtility.GetOriginalFilePath(SubFolder, image, (SubFolder == @"Animal" ? AppUserId : 0));
            }
            else
            {
                path = MediaUtility.GetImageFilePath(SubFolder, image, w, h, (SubFolder == @"Animal" ? AppUserId : 0));
            }

            if (path.Length > 0 && File.Exists(path))
            {
                Response.Cache.SetMaxAge(TimeSpan.FromDays(30));
                Response.Cache.SetCacheability(HttpCacheability.Public);
                Response.ClearContent();

                string mimeType = @"image";
                if (image.EndsWith(@".jpg", StringComparison.OrdinalIgnoreCase))
                {
                    mimeType = @"image/jpg";
                }
                else if (image.EndsWith(@".jpeg", StringComparison.OrdinalIgnoreCase))
                {
                    mimeType = @"image/jpeg";
                }
                else if (image.EndsWith(@".png", StringComparison.OrdinalIgnoreCase))
                {
                    mimeType = @"image/png";
                }
                else if (image.EndsWith(@".gif", StringComparison.OrdinalIgnoreCase))
                {
                    mimeType = @"image/gif";
                }
                else if (image.EndsWith(@".mp4", StringComparison.OrdinalIgnoreCase))
                {
                    mimeType = @"video/mp4";
                }
                else if (image.EndsWith(@".mpg", StringComparison.OrdinalIgnoreCase))
                {
                    mimeType = @"video/mpeg";
                }

                Response.ContentType = mimeType;
                Response.AddFileDependency(path);
                Response.Cache.SetLastModifiedFromFileDependencies();
                Response.Cache.SetETagFromFileDependencies();

                if (IsHead)
                {
                    Response.AddHeader(@"Content-Length", new FileInfo(path).Length.ToString());
                }
                else
                {
                    Response.TransmitFile(path);
                }

                return;
            }
            else
            {
                Response.StatusCode = 404;
                return;
            }
        }
示例#13
0
        public override void Get(HttpRequest Request, HttpResponse Response, params string[] PathParams)
        {
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetMaxAge(TimeSpan.Zero);

            Int64  AppUserId     = 0;
            string SubFolder     = Request.QueryString["sub_folder"] != null ? Request.QueryString["sub_folder"].ToString() : "";
            Int64  TempAppUserId = (Request.QueryString["temp_app_user_id"] != null ? Convert.ToInt64(Request.QueryString["temp_app_user_id"]) : 0);

            bool isAuthorized = IsAuthorizedRequest(Request, Response, false, out AppUserId) || TempAppUserId > 0;

            if (Request.QueryString[@"image"].Contains("2018_03_19_12_05_04") && isAuthorized)
            {
                NotificationFilter filter = null;
                if (AppUserId > 0)
                {
                    filter = NotificationGroups.GetUserRelevantFilter(AppUserId);
                }
                else if (TempAppUserId > 0)
                {
                    filter = NotificationGroups.GetTempUserFilter();
                }

                if (filter != null)
                {
                    string image = filter.AdImageUrl;
                    string path  = MediaUtility.GetOriginalFilePath(SubFolder, filter.AdImageUrl, 0);
                    if (path.Length > 0 && File.Exists(path))
                    {
                        Response.Cache.SetMaxAge(TimeSpan.FromDays(30));
                        Response.Cache.SetCacheability(HttpCacheability.Public);
                        Response.ClearContent();

                        string mimeType = @"image";
                        if (image.EndsWith(@".jpg", StringComparison.OrdinalIgnoreCase))
                        {
                            mimeType = @"image/jpg";
                        }
                        else if (image.EndsWith(@".jpeg", StringComparison.OrdinalIgnoreCase))
                        {
                            mimeType = @"image/jpeg";
                        }
                        else if (image.EndsWith(@".png", StringComparison.OrdinalIgnoreCase))
                        {
                            mimeType = @"image/png";
                        }
                        else if (image.EndsWith(@".gif", StringComparison.OrdinalIgnoreCase))
                        {
                            mimeType = @"image/gif";
                        }

                        Response.ContentType = mimeType;
                        Response.AddFileDependency(path);
                        Response.Cache.SetLastModifiedFromFileDependencies();
                        Response.Cache.SetETagFromFileDependencies();
                        Response.TransmitFile(path);
                        return;
                    }
                }
            }

            if (SubFolder == "Product" || SubFolder == "ProductYad2" || SubFolder == "Banners" || SubFolder == "Supplier")
            {
                HandleImageRequest(Request, Response, false, 0, SubFolder);
            }
            else if (AppUserId > 0 || IsAuthorizedRequest(Request, Response, true, out AppUserId))
            {
                HandleImageRequest(Request, Response, false, AppUserId, SubFolder);
            }
        }