Beispiel #1
0
        /// <summary>
        /// Outputs the combined script file requested by the HttpRequest to the HttpResponse
        /// </summary>
        /// <param name="context">HttpContext for the transaction</param>
        /// <returns>true if the script file was output</returns>
        public static bool OutputCombinedScriptFile(HttpContext context)
        {
            // Initialize
            bool        output          = false;
            HttpRequest request         = context.Request;
            string      hiddenFieldName = request.Params[HiddenFieldParamName];
            string      combinedScripts = request.Params[CombinedScriptsParamName];

            if (!string.IsNullOrEmpty(hiddenFieldName) && !string.IsNullOrEmpty(combinedScripts))
            {
                // This is a request for a combined script file
                HttpResponse response = context.Response;
                response.ContentType = "application/x-javascript";

                // Set the same (~forever) caching rules that ScriptResource.axd uses
                HttpCachePolicy cache = response.Cache;
                cache.SetCacheability(HttpCacheability.Public);
                cache.VaryByParams[HiddenFieldParamName]     = true;
                cache.VaryByParams[CombinedScriptsParamName] = true;
                cache.SetOmitVaryStar(true);
                cache.SetExpires(DateTime.Now.AddDays(365));
                cache.SetValidUntilExpires(true);
                cache.SetLastModifiedFromFileDependencies();

                // Get the stream to write the combined script to (using a compressed stream if requested)
                // Note that certain versions of IE6 have difficulty with compressed responses, so we
                // don't compress for those browsers (just like ASP.NET AJAX's ScriptResourceHandler)
                Stream outputStream = response.OutputStream;
                if (!request.Browser.IsBrowser("IE") || (6 < request.Browser.MajorVersion))
                {
                    foreach (string acceptEncoding in (request.Headers["Accept-Encoding"] ?? "").ToUpperInvariant().Split(','))
                    {
                        if ("GZIP" == acceptEncoding)
                        {
                            // Browser wants GZIP; wrap the output stream with a GZipStream
                            response.AddHeader("Content-encoding", "gzip");
                            outputStream = new GZipStream(outputStream, CompressionMode.Compress);
                            break;
                        }
                        else if ("DEFLATE" == acceptEncoding)
                        {
                            // Browser wants Deflate; wrap the output stream with a DeflateStream
                            response.AddHeader("Content-encoding", "deflate");
                            outputStream = new DeflateStream(outputStream, CompressionMode.Compress);
                            break;
                        }
                    }
                }

                // Output the combined script
                using (StreamWriter outputWriter = new StreamWriter(outputStream))
                {
                    // Get the list of scripts to combine
                    List <ScriptEntry> scriptEntries = DeserializeScriptEntries(HttpUtility.UrlDecode(combinedScripts), false);

                    // Write the scripts
                    WriteScripts(scriptEntries, outputWriter);

                    // Write the ASP.NET AJAX script notification code
                    outputWriter.WriteLine("if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();");

                    // Write a handler to run on page load and update the hidden field tracking scripts loaded in the browser
                    outputWriter.WriteLine(string.Format(CultureInfo.InvariantCulture,
                                                         "(function() {{" +
                                                         "var fn = function() {{" +
                                                         "$get('{0}').value += '{1}';" +
                                                         "Sys.Application.remove_load(fn);" +
                                                         "}};" +
                                                         "Sys.Application.add_load(fn);" +
                                                         "}})();", hiddenFieldName, SerializeScriptEntries(scriptEntries, true)));
                }

                output = true;
            }
            return(output);
        }
Beispiel #2
0
        public ActionResult ProcessRequest()
        {
            var Request = HttpContext.Request;

            string resourceSet = Request.Query["ResourceSet"];


            string localeId = Request.Query["LocaleId"];

            if (string.IsNullOrEmpty(localeId))
            {
                localeId = "auto";
            }
            string resourceMode = Request.Query["ResourceMode"];

            if (string.IsNullOrEmpty(resourceMode))
            {
                resourceMode = "Resx"; // Resx/ResDb/Auto
            }
            string varname = Request.Query["VarName"];

            if (string.IsNullOrEmpty(varname))
            {
                varname = "resources";
            }

            // varname is embedded into script so validate to avoid script injection
            // it's gotta be a valid C# and valid JavaScript name
            Match match = Regex.Match(varname, @"^[\w|\d|_|$|@|\.]*$");

            if (match.Length < 1 || match.Groups[0].Value != varname)
            {
                SendErrorResponse("Invalid variable name passed.");
            }

            if (string.IsNullOrEmpty(resourceSet))
            {
                SendErrorResponse("Invalid ResourceSet specified.");
            }

            // pick current UI Culture
            if (localeId == "auto")
            {
                try
                {
                    // Use ASP.NET Core RequestLocalization Mapping
                    var cultureProvider = HttpContext.Features.Get <IRequestCultureFeature>();
                    if (cultureProvider != null)
                    {
                        localeId = cultureProvider.RequestCulture.UICulture.IetfLanguageTag;
                    }
                    else
                    {
                        localeId = Thread.CurrentThread.CurrentUICulture.IetfLanguageTag;
                    }
                }
                catch
                {
                    localeId = Thread.CurrentThread.CurrentUICulture.IetfLanguageTag;
                }
            }

            Dictionary <string, object> resDict = null;

            resourceMode = string.IsNullOrEmpty(resourceMode) ? "auto" : resourceMode.ToLower();

            ResourceAccessMode mode = ResourceAccessMode.Resx;

            if (resourceMode == "resdb")
            {
                mode = ResourceAccessMode.DbResourceManager;
            }
            else if (resourceMode == "auto")
            {
                mode = DbResourceConfiguration.Current.ResourceAccessMode;
            }


            if (mode == ResourceAccessMode.DbResourceManager)
            {
                var resManager = DbResourceDataManager.CreateDbResourceDataManager(
                    Config.DbResourceDataManagerType);
                resDict = resManager.GetResourceSetNormalizedForLocaleId(localeId, resourceSet);
                if (resDict == null || resDict.Count == 0)
                {
                    mode = ResourceAccessMode.Resx; // try Resx resources from disk instead
                }
            }

            if (mode != ResourceAccessMode.DbResourceManager) // Resx Resources loaded from disk
            {
                string basePath = Request.MapPath(DbResourceConfiguration.Current.ResxBaseFolder,
                                                  basePath: Host.ContentRootPath);
                DbResXConverter converter = new DbResXConverter(basePath);

                resDict = converter.GetCompiledResourcesNormalizedForLocale(resourceSet,
                                                                            DbResourceConfiguration.Current.ResourceBaseNamespace,
                                                                            localeId);

                if (resDict == null)
                {
                    // check for .resx disk resources
                    string resxPath = converter.FormatResourceSetPath(resourceSet);
                    resDict = converter.GetResXResourcesNormalizedForLocale(resxPath, localeId);
                }
                else
                {
                    resDict = resDict.OrderBy(kv => kv.Key).ToDictionary(k => k.Key, v => v.Value);
                }
            }

            // return all resource strings
            resDict = resDict.Where(res => res.Value is string)
                      .ToDictionary(dict => dict.Key, dict => dict.Value);

            string javaScript = SerializeResourceDictionary(resDict, varname);



#if NETFULL // client cache
            if (!HttpContext.Current.IsDebuggingEnabled)
            {
                Response.ExpiresAbsolute = DateTime.UtcNow.AddDays(1);
                Response.AppendHeader("Accept-Ranges", "bytes");
                Response.AppendHeader("Vary", "Accept-Encoding");
                Response.Cache.SetETag("\"" + javaScript.GetHashCode().ToString("x") + "\"");
                Response.Cache.SetLastModified(DateTime.UtcNow);

                // OutputCache settings
                HttpCachePolicy cache = Response.Cache;

                cache.VaryByParams["ResourceSet"]     = true;
                cache.VaryByParams["LocaleId"]        = true;
                cache.VaryByParams["ResoureType"]     = true;
                cache.VaryByParams["IncludeControls"] = true;
                cache.VaryByParams["VarName"]         = true;
                cache.VaryByParams["ResourceMode"]    = true;
                //cache.SetOmitVaryStar(true);

                DateTime now = DateTime.Now;
                cache.SetCacheability(HttpCacheability.Public);
                cache.SetExpires(now + TimeSpan.FromDays(1));
                cache.SetValidUntilExpires(true);
                cache.SetLastModified(now);
            }
#endif

            return(SendTextOutput(javaScript, "text/javascript; charset=utf-8"));
        }
Beispiel #3
0
        /// <summary>
        /// Configures ASP.Net's Cache policy based on properties set
        /// </summary>
        /// <param name="policy">cache policy to set</param>
        void ICachePolicyConfigurer.Configure(HttpCachePolicy policy)
        {
            policy.SetAllowResponseInBrowserHistory(allowInHistory);
            policy.SetCacheability(cacheability);
            policy.SetOmitVaryStar(omitVaryStar);
            policy.SetRevalidation(revalidation);
            policy.SetSlidingExpiration(slidingExpiration);
            policy.SetValidUntilExpires(validUntilExpires);

            if (duration != 0)
            {
                policy.SetExpires(DateTime.Now.AddSeconds(duration));
            }

            if (varyByContentEncodings != null)
            {
                foreach (var header in varyByContentEncodings.Split(','))
                {
                    policy.VaryByContentEncodings[header.Trim()] = true;
                }
            }

            if (varyByCustom != null)
            {
                policy.SetVaryByCustom(varyByCustom);
            }

            if (varyByHeaders != null)
            {
                foreach (var header in varyByHeaders.Split(','))
                {
                    policy.VaryByHeaders[header.Trim()] = true;
                }
            }

            if (varyByParams != null)
            {
                foreach (var param in varyByParams.Split(','))
                {
                    policy.VaryByParams[param.Trim()] = true;
                }
            }

            if (cacheExtension != null)
            {
                policy.AppendCacheExtension(cacheExtension);
            }

            if (setEtagFromFileDependencies)
            {
                policy.SetETagFromFileDependencies();
            }

            if (setLastModifiedFromFileDependencies)
            {
                policy.SetLastModifiedFromFileDependencies();
            }

            if (setNoServerCaching)
            {
                policy.SetNoServerCaching();
            }

            if (setNoStore)
            {
                policy.SetNoStore();
            }

            if (setNoTransforms)
            {
                policy.SetNoTransforms();
            }

            if (etag != null)
            {
                policy.SetETag(etag);
            }

            if (isLastModifiedSet)
            {
                policy.SetLastModified(lastModified);
            }

            if (isMaxAgeSet)
            {
                policy.SetMaxAge(TimeSpan.FromSeconds(maxAge));
            }

            if (isProxyMaxAgeSet)
            {
                policy.SetProxyMaxAge(TimeSpan.FromSeconds(proxyMaxAge));
            }
        }
Beispiel #4
0
        public void Deny_Unrestricted()
        {
            HttpCachePolicy cache = response.Cache;

            Assert.IsNotNull(cache.VaryByHeaders, "VaryByHeaders");
            Assert.IsNotNull(cache.VaryByParams, "VaryByParams");
            cache.AddValidationCallback(new HttpCacheValidateHandler(Validate), null);
            cache.AppendCacheExtension("mono");
            cache.SetCacheability(HttpCacheability.NoCache);
            cache.SetCacheability(HttpCacheability.NoCache, "mono");
            cache.SetETag("etag");
            try {
                cache.SetETagFromFileDependencies();
            }
            catch (TypeInitializationException) {
                // 1.1 tries to initialize HttpRuntime
            }
            catch (InvalidOperationException) {
                // expected
            }
            cache.SetExpires(DateTime.MinValue);
            cache.SetLastModified(DateTime.Now);
            try {
                cache.SetLastModifiedFromFileDependencies();
            }
            catch (InvalidOperationException) {
                // expected
            }
            catch (NotImplementedException) {
                // mono
            }
            cache.SetMaxAge(TimeSpan.FromTicks(1000));
            try {
                cache.SetNoServerCaching();
            }
            catch (NotImplementedException) {
                // mono
            }
            try {
                cache.SetNoStore();
            }
            catch (NotImplementedException) {
                // mono
            }
            try {
                cache.SetNoTransforms();
            }
            catch (NotImplementedException) {
                // mono
            }
            cache.SetProxyMaxAge(TimeSpan.FromTicks(2000));
            cache.SetRevalidation(HttpCacheRevalidation.None);
            cache.SetSlidingExpiration(true);
            try {
                cache.SetValidUntilExpires(true);
            }
            catch (NotImplementedException) {
                // mono
            }
            cache.SetVaryByCustom("custom");
            cache.SetAllowResponseInBrowserHistory(true);

#if NET_2_0
            try {
                cache.SetOmitVaryStar(false);
            }
            catch (NotImplementedException) {
                // mono
            }
#endif
        }
 public override void SetValidUntilExpires(bool validUntilExpires)
 {
     _policy.SetValidUntilExpires(validUntilExpires);
 }
Beispiel #6
0
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest request     = context.Request;
            string      phyFilePath = request.PhysicalPath;

            if (!File.Exists(phyFilePath))
            {
                string phyDirPath = Path.GetDirectoryName(phyFilePath);
                if (!string.IsNullOrWhiteSpace(phyDirPath))
                {
                    string fileName = Path.GetFileNameWithoutExtension(phyFilePath);
                    if (!string.IsNullOrWhiteSpace(fileName))
                    {
                        string fileExtension = Path.GetExtension(phyFilePath);
                        if (!string.IsNullOrWhiteSpace(fileExtension))
                        {
                            string[] fileNames = fileName.Split(new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries);
                            if (fileNames != null)
                            {
                                int length = fileNames.Length;
                                if (length > 1)
                                {
                                    fileName    = string.Join("_", fileNames, 0, length - 1);
                                    phyFilePath = Path.Combine(phyDirPath, string.Concat(fileName, fileExtension));
                                }
                                Array.Clear(fileNames, 0, length);
                                fileNames = null;
                            }
                            fileExtension = null;
                        }
                        fileName = null;
                    }
                    phyDirPath = null;
                }
            }
            if (File.Exists(phyFilePath))
            {
                HttpResponse response  = context.Response;
                ECacheType   cacheType = ECacheType.None;
                string       subfix    = Path.GetExtension(phyFilePath);
                if (".css".Equals(subfix, StringComparison.CurrentCultureIgnoreCase))
                {
                    cacheType            = ECacheType.Css;
                    response.ContentType = "text/css";
                }
                else if (".js".Equals(subfix, StringComparison.CurrentCultureIgnoreCase))
                {
                    cacheType            = ECacheType.Js;
                    response.ContentType = "application/x-javascript";
                }
#if !DEBUG
                if (cacheType != ECacheType.None)
                {
                    //http://www.cnblogs.com/shanyou/archive/2012/05/01/2477500.html
                    const int DAYS            = 30;
                    string    ifModifiedSince = request.Headers["If-Modified-Since"];
                    if (!string.IsNullOrEmpty(ifModifiedSince) &&
                        TimeSpan.FromTicks(DateTime.Now.Ticks - DateTime.Parse(ifModifiedSince).Ticks).Days < DAYS)
                    {
                        response.StatusCode        = (int)System.Net.HttpStatusCode.NotModified;
                        response.StatusDescription = "Not Modified";
                        response.End();
                        return;
                    }
                    else
                    {
                        string fileContent = null;
                        string ifNoneMatch = request.Headers["If-None-Match"];
                        string eTag        = string.Format("\"{0}\"", this.GetFileMd5(string.Concat(phyFilePath, fileContent = this.GetFileContent(phyFilePath))));
                        if (!string.IsNullOrEmpty(ifNoneMatch) && ifNoneMatch.Equals(eTag))
                        {
                            response.StatusCode        = (int)System.Net.HttpStatusCode.NotModified;
                            response.StatusDescription = "Not Modified";
                            response.End();
                            return;
                        }
                        else
                        {
                            HttpCachePolicy cache = response.Cache;
                            //cache.SetLastModifiedFromFileDependencies();//程序自动读取文件的LastModified
                            cache.SetLastModified(context.Timestamp); //因为静态文件的URL是特殊处理过,所以程序自动读取文件是在磁盘上找不到的,故改成手工代码设置文件的LastModified的方式。wangyunpeng,2016-4-12
                            //cache.SetETagFromFileDependencies();//程序自动读取文件的ETag
                            cache.SetETag(eTag);                      //因为静态文件的URL是特殊处理过,所以程序自动读取文件是在磁盘上找不到的,故改成手工代码设置文件的ETag的方式。wangyunpeng,2016-4-12
                            cache.SetCacheability(HttpCacheability.Public);
                            cache.SetExpires(DateTime.Now.AddDays(DAYS));
                            TimeSpan timeSpan = TimeSpan.FromDays(DAYS);
                            cache.SetMaxAge(timeSpan);
                            cache.SetProxyMaxAge(timeSpan);
                            cache.SetValidUntilExpires(true);
                            cache.SetSlidingExpiration(true);
                            #region 压缩js和css文件
                            if (!string.IsNullOrWhiteSpace(fileContent))
                            {
                                if (cacheType == ECacheType.Js)
                                {
                                    string fileName = Path.GetFileName(phyFilePath);
                                    if (_MiniJsFiles.Contains(fileName, new StringComparer()))
                                    {
                                        fileContent = this.PackJavascript(fileContent);//ECMAScript压缩
                                    }
                                }
                                //输出内容
                                response.ContentEncoding = _GlobalizationSection == null ? Encoding.UTF8 : _GlobalizationSection.ResponseEncoding;
                                response.Write(fileContent);
                            }
                            #endregion
                        }
                    }
                }
                else
                {//直接输出文件
                    response.WriteFile(phyFilePath);
                }
#else
                //直接输出文件
                response.WriteFile(phyFilePath);
#endif
                //取消GZIP压缩,IE7,IE8,Safari支持GZIP压缩显示css和js有问题。wangyunpeng
                if (this.IsAcceptEncoding(request, GZIP))
                {
                    response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
                    this.SetResponseEncoding(response, GZIP);
                }
                else if (this.IsAcceptEncoding(request, DEFLATE))
                {
                    response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
                    this.SetResponseEncoding(response, DEFLATE);
                }
                response.End();
            }
        }
Beispiel #7
0
        /// <summary>
        /// 将文件内容输出到客户端客户端浏览器,支持http头操作。
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        /// <param name="fileContent">要往客户端浏览器输出的文本内容</param>
        /// <param name="isHttpHead">True表示使用http头操作,False表示不使用http头操作</param>
        internal static void Output(HttpRequest request, HttpResponse response, string fileContent, string absoluteFilePath, bool isHttpHead)
        {
            if (string.IsNullOrWhiteSpace(fileContent))
            {
                return;
            }
            //wangyunpeng 增加http头,把生成的路径输出出来,方便修改页面使用。
            if (absoluteFilePath != null)
            {
                response.AddHeader("X-Page-Hash", absoluteFilePath);
            }
            HttpCachePolicy cache = response.Cache;

            cache.SetOmitVaryStar(true);//http://www.cnblogs.com/dudu/archive/2011/11/03/outputcache_Bug_vary.html
//#if DEBUG
            //本地调试不使用浏览器缓存
            //cache.SetCacheability(HttpCacheability.NoCache);
            //cache.SetExpires(DateTime.UtcNow.AddYears(-1));
            //cache.SetMaxAge(TimeSpan.Zero);
            //cache.SetProxyMaxAge(TimeSpan.Zero);
            //cache.SetNoServerCaching();
            //cache.SetNoStore();
            //cache.SetNoTransforms();
//#else
            string ifModifiedSince = request.Headers["If-Modified-Since"];

            if (isHttpHead)
            {
                if (
                    !string.IsNullOrWhiteSpace(ifModifiedSince) &&
                    TimeSpan.FromTicks(DateTime.Now.Ticks - TypeParseHelper.StrToDateTime(ifModifiedSince).Ticks).Minutes < CACHE_DATETIME)
                {
                    response.StatusCode        = (int)System.Net.HttpStatusCode.NotModified;
                    response.StatusDescription = "Not Modified";
                    response.End();
                    return;
                }
                else
                {
                    cache.SetLastModifiedFromFileDependencies();
                    cache.SetETagFromFileDependencies();
                    cache.SetCacheability(HttpCacheability.Public);
                    cache.SetExpires(DateTime.UtcNow.AddMinutes(CACHE_DATETIME));
                    TimeSpan timeSpan = TimeSpan.FromMinutes(CACHE_DATETIME);
                    cache.SetMaxAge(timeSpan);
                    cache.SetProxyMaxAge(timeSpan);
                    cache.SetLastModified(DateTime.Now);
                    cache.SetValidUntilExpires(true);
                    cache.SetSlidingExpiration(true);
                }
            }

//#endif
            System.Text.Encoding encoding = IOHelper.GetHtmEncoding(fileContent) ?? NVelocityBus._GlobalizationSection.ResponseEncoding;
            response.ContentEncoding = encoding;
            response.ContentType     = response.ContentType;
            response.Write(fileContent);

            //压缩页面
            if (request.ServerVariables["HTTP_X_MICROSOFTAJAX"] == null)
            {
                if (NVelocityBus.IsAcceptEncoding(request, GZIP))
                {
                    response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
                    NVelocityBus.SetResponseEncoding(response, GZIP);
                }
                else if (NVelocityBus.IsAcceptEncoding(request, DEFLATE))
                {
                    response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
                    NVelocityBus.SetResponseEncoding(response, DEFLATE);
                }
            }
            //强制结束输出
            response.End();
        }