zoukankan      html  css  js  c++  java
  • 利用Ihttpmodel实现网站缓存,解决Server.Transfer 直接输出HTML源代码的问题

    今天在用.NET利用IHttpModel实现网站静态缓存的时候,不知道最后为什么用 Server.Transfer(html)的时候结果输出的是HTML的源代码。

    贴上源代码

    using System;
    using System.Web;
    using System.Text.RegularExpressions;
    using System.IO;
    using System.Configuration;
    using System.Collections.Generic;
    namespace Product
    {
        public class ProductModule : IHttpModule
        {
            public void Init(HttpApplication application)
            {
                application.BeginRequest += (new EventHandler(this.Application_BeginRequest));//请求开始
                application.EndRequest += (new EventHandler(this.Application_EndRequest));//请求结束
            }
            private void Application_BeginRequest(Object source, EventArgs e)
            {
                HttpApplication Application = (HttpApplication)source;
                CheckUrl(Application);
            }
            private void Application_EndRequest(Object source, EventArgs e)
            {
                //HttpApplication Application = (HttpApplication)source;
                //Application.Response.Write("test");
            }
            private void CheckUrl(HttpApplication application)
            {
                if (application.Request.RequestType.ToUpper() == "POST" || application.Request.UserAgent.ToLower() == "product")
                {
                    return;
                }
    
                string[] resUrlTemp = new string[5];//待缓存的请求模板
                resUrlTemp[0] = "/model/modelsearch.aspx\?clid=([\d]+)&coid=([\d]+)&bid=([\d]+)&price=(.*)&model=(.*)&p=([\d]+)&t=([0-2]{1,1})";
                resUrlTemp[1] = "/pic/imgsearch.aspx\?clid=([\d]+)&cbid=([\d]+)&model=(.*)&p=([\d]+)";
                resUrlTemp[2] = "/praise/PraiseSearch.aspx\?clid=([\d]+)&coid=([\d]+)&model=(.*)&p=([\d]+)";
                resUrlTemp[3] = "/price/sellerpricesearch.aspx\?clid=([\d]+)&coid=([\d]+)&brand=([\d]+)&price=(.*)&model=(.*)&p=([\d]+)&t=([0-2]{1,1})";
                resUrlTemp[4] = "/dealer/sellersearch.aspx\?pve=([\d]+)&city=([\d]+)&type=([\d]+)&seller=(.*)&bid=([\d]+)&model=(.*)&pagesize=([\d]+)&p=([\d]+)";
    
                string reqUrl = application.Context.Request.Url.PathAndQuery.ToLower();//请求动态路径
                
    
                bool success = false;
                for (int i = 0; i < resUrlTemp.Length;i++ )
                {
                    if (!success)
                    {
                        Regex reg = new Regex(resUrlTemp[i]);//匹配当前请求是否需要缓存
                        MatchCollection mc = reg.Matches(reqUrl);
                        if (mc.Count > 0)
                        {
                            //静态页命名使用当前请求路径MD5加密命名
                            string PyReUrl = ConfigurationManager.ConnectionStrings["WebPhysicsUrl"].ConnectionString + "/Cache/" + i + "/" + System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(reqUrl, "MD5") + ".html";
    
    
                            FileInfo fi = new FileInfo(PyReUrl);//判断是否缓存
                            if (!fi.Exists)
                            {
                                //缓存页面
                                string WebUrl = ConfigurationManager.ConnectionStrings["WebUrl"].ConnectionString;
                                System.Net.HttpWebRequest Request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(WebUrl + reqUrl);//Post请求当前页
                                Request.Method = "GET";
                                Request.Accept = "*/*";
                                Request.UserAgent = "Product";
                                Request.AllowAutoRedirect = true;
                                Request.MaximumAutomaticRedirections = 2;
    
                                System.Net.HttpWebResponse Response = null;
                                try
                                {
                                    Response = (System.Net.HttpWebResponse)Request.GetResponse();//获得响应
                                }
                                catch(Exception ex)
                                {
                                    application.Response.Write("Response Error"+ex.Message);
                                }
                                if (Response != null)
                                {
                                    System.IO.Stream strm = Response.GetResponseStream();
                                    System.IO.StreamReader sr = new System.IO.StreamReader(strm, System.Text.Encoding.GetEncoding("gb2312"));
    
    
                                    StreamWriter Sw = null;
                                    try
                                    {
                                        if (!Directory.Exists(Directory.GetParent(PyReUrl).FullName))
                                            Directory.CreateDirectory(Directory.GetParent(PyReUrl).FullName);
    
                                        FileStream Fs = new FileStream(PyReUrl, FileMode.Create, FileAccess.Write, FileShare.Read);
                                        Sw = new StreamWriter(Fs, System.Text.Encoding.Default, 512);
    
                                        Sw.Write(sr.ReadToEnd());//写入
    
                                        success = true;
                                    }
                                    catch(Exception ex)
                                    {
                                        Sw.Close();
                                        application.Response.Write("Writer Error"+ex.Message);
                                    }
    
                                    sr.Close();
                                    Sw.Close();
                                    Response.Close();
                                }
                            }
                            else
                            {
                                //application.Response.Redirect(PyReUrl);//链接到静态页面 浏览器请求路径不变,不会影响收录
                                application.Server.Transfer("/Cache/" + i + "/" + System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(reqUrl, "MD5") + ".html");
                            }
                        }
                    }
                }
                    
            }
            public void Dispose()
            {
            }
        }
    }

    我的问题是这样的,我的网站采用的UTF8编码

    当这两个流采用gb2312的时候,Service.Transfer是可以正常显示HTMl的,但是页面乱码

      System.IO.Stream strm = Response.GetResponseStream();  
      System.IO.StreamReader sr = new System.IO.StreamReader(strm, System.Text.Encoding.GetEncoding("gb2312"));  
     FileStream Fs = new FileStream(PyReUrl, FileMode.Create, FileAccess.Write, FileShare.Read);  
     Sw = new StreamWriter(Fs, System.Text.Encoding.Default, 512);  

    但是当我采用UTF编码的时候,页面缓存没问题,但是Service.Transfer就只是显示源代码,不知道为什么。求解。

    此贴用于记录,如果找到解决方案后,我会贴出来!

    个人解决方案:

    个人觉得很误解,问了好多人,都没有遇到过这种情况,不知道是不是只有我一个人遇到过。。。。。。。

    说下个人的解决办法把。

    上代码

    application.Response.Write(File.ReadAllText(application.Server.MapPath("/cache/" + i + "/" + System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(reqUrl, "MD5") + ".html")));
    application.Response.End();

    我首先读取缓存文件的内容,然后用write去写,暂时就这样吧。以后如果有好的解决方案了,在做修改!

  • 相关阅读:
    安装mysql_cluster报错: Data::Dumper丢失
    win10 nodejs指定ionic版本安装(npm方式)
    java项目报错: org.springframework.beans.factory.BeanCreationException找不到mapper.xml文件
    java项目跑起来报错: 程序报 SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". 错误
    ~/.bashrc文件写错, 导致Linux全部命令丢失
    tomcat热启动没问题, 访问项目报500解决办法
    安装OpenOffice
    redhat6.4 elasticsearch1.7.3安装配置
    MySQL新建用户保存的时报错:The MySQL server is running with the --skip-grant-tables option so it cannot execute this statement
    zabbix zabbix_agentd.conf详解
  • 原文地址:https://www.cnblogs.com/dazhuangtage/p/4778343.html
Copyright © 2011-2022 走看看