zoukankan      html  css  js  c++  java
  • ASP.Net零碎

    ASP.Net零碎

    ServerPush

    什么是ServerPush,服务器向客户端浏览器“推送”,其实就是“长连接”。
    只有浏览器请求服务器端,服务器端才有给浏览器响应数据,不会主动向浏览器推送数据,这样是安全考虑,也是提高服务器的性能考虑。如果要服务器向浏览器推送数据,则需要使用ServerPush等技术模拟实现。
    通过两个页面互相发送消息来实现,消息放到数据库。
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title></title>
        <script src="jquery-2.1.1.js"></script>
        <script type="text/javascript">
            $(function () {
                $("#send").click(function () {
                    var me = $("#me").val();
                    var tousername = $("#tousername").val();
                    var msgs = $("#msgs").val();
                    $.ajax({
                        type: "post", url: "ServerPush.ashx",
                        data: { action: "send", me: me, tousername: tousername, msgs: msgs },
                        success: function (data) {
                            if (data.Status =="ok" )
                            {
                                $("#ulMs").append($("<li>我对" + tousername + "说:" + msgs + "</li>"));
                                $("#msgs").val("");
                            }
                            else {
                                alert("发送出错,返回报文无法识别");
                            }
                        },
                        error: function () {
                            alert("发送出错");
                        }
                    })
                })
                $("#lode").click(function () {
                    var me = $("#me").val();
                    $.ajax({
                        type: "post", url: "ServerPush.ashx", data: { action: "serve", me: me },
                        success: function (data) {
                            $("#ulMs").append($("<li>" + data.Fromsername + "我对说:" + data.Msga + "</li>"));
                        },
                        error: function () {
                            alert("发送出错");
                        }
                    })
                    })
            })
        </script>
       
    </head>
    <body>
        发送者:<input type="text" id="me" />
        <input type="button" id="lode" value="登陆" /><br />
        接受者<input type="text" id="tousername" />
        说:<input type="text" id="msgs" />
        <input type="button" id="send" value="发送" />
        <ul id="ulMs"></ul>
    </body>
            //Id, Tousername, Fromusername, Msgs
            public void ProcessRequest(HttpContext context)
            {
                context.Response.ContentType = "application/json";
                string action = context.Request["action"];//判断是接受还是发送
                if (action == "send")
                {
                    string me = context.Request["me"];
                    string tousername = context.Request["tousername"];
                    string msg = context.Request["msgs"];
                    SQLHelper.SqlEffectRow("insert into Msg(Fromusername,Tousername,Msgs) values(@FromUserName,@ToUserName,@Msg)", new SqlParameter("@FromUserName", me), new SqlParameter("@ToUserName", tousername), new SqlParameter("@Msg", msg));//新增消息
                    context.Response.Write(new JavaScriptSerializer().Serialize(new{Status="ok"}) );
                }
                else if(action=="serve")
                {
                    string me = context.Request["me"];
                    while (true)
                    {
                        DataTable Dt = SQLHelper.SQLDataTable("select top 1 * from Msg where Tousername=@Tousername", new SqlParameter("@Tousername", me));
                        if (Dt.Rows.Count <= 0)
                        {
                            Thread.Sleep(500);//休息500毫秒,减轻服务器压力
                            continue;
                        }
                        else
                        {
                            int id = (int)Dt.Rows[0]["Id"];
                            string fromsername = (string)Dt.Rows[0]["Fromusername"];
                            string msgs = (string)Dt.Rows[0]["Msgs"];
                            SQLHelper.SqlEffectRow("delete from Msg where Id=@Id", new SqlParameter("@Id", id));//保存后删除该条消息,避免重复
                            var data = new { Fromsername = fromsername, Msga = msgs };
                            string json = new JavaScriptSerializer().Serialize(data);//json
                            context.Response.Write(json);
                            break;
                        }
                    }
                }

     Global

    Session_Start()和Session_End(),进程外Session不会触发Session_End()。重点:Application_Start、Application_BeginRequest、Application_Error。
    UrlRewrite:
     View.aspx?id=1→View-1.aspx
     在BeginRequest中获取请求的url( HttpContext.Current.Request.RawUrl ),生成真正的地址( Context.RewritePath ())
     静态文件等默认是不经过asp.net引擎处理的,因此不会经过Global。
     1 namespace Web1
     2 {
     3     public class Global : System.Web.HttpApplication
     4     {
     5         //自从服务器启动起来,网站第一次被访问的时候Application_Start执行
     6         protected void Application_Start(object sender, EventArgs e)
     7         {
     8             File.AppendAllText("d:\1.txt", DateTime.Now+"Application_Start
    ");
     9         }
    10  
    11         //Session启动时
    12         protected void Session_Start(object sender, EventArgs e)
    13         {
    14             File.AppendAllText("d:\1.txt", DateTime.Now + "Session_Start
    ");
    15         }
    16  
    17         //当一个请求过来的时候
    18         //html等静态文件是iis直接把文件给到浏览器,不经过asp.net引擎的处理。
    19         //所以不会调用Application_BeginRequest方法
    20         protected void Application_BeginRequest(object sender, EventArgs e)
    21         {
    22             //即使用户访问一个不存在的页面,那么Application_BeginRequest也会被调用
    23  
    24             File.AppendAllText("d:\1.txt", DateTime.Now + "Application_BeginRequest:"+
    25                 Context.Request.RawUrl + "
    ");
    26             //Context.RewritePath("WebExcel.html");//请求重写在服务器内部发生
    27             //File.AppendAllText("d:\1.txt", DateTime.Now + "Context.Request.Path:" +
    28                 //Context.Request.Path + "
    ");
    29  
    30             int? count =(int?)Application.Get("Count");
    31             if (count == null)
    32             {
    33                 count = 1;
    34             }
    35             count++;
    36             Application.Lock();
    37             Application.Set("Count", count);
    38             Application.UnLock();
    39  
    40             //Url重写:UrlRewrite。ViewPerson-1.aspx
    41             Match match = Regex.Match(Context.Request.Path, @"^/ViewPerson-(d+).aspx$");
    42             if (match.Success)
    43             {
    44                string id = match.Groups[1].Value;
    45                Context.RewritePath("/ViewPerson.aspx?id="+id);
    46             }
    47         }
    48  
    49         protected void Application_AuthenticateRequest(object sender, EventArgs e)
    50         {
    51  
    52         }
    53  
    54         //程序中发生未处理异常
    55         protected void Application_Error(object sender, EventArgs e)
    56         {
    57             File.AppendAllText("d:\1.txt", DateTime.Now + "Application_Error:"+
    58                 Context.Error + "
    ");
    59         }
    60  
    61         //(*)Session过期(只有进程内Session,也就是InProc过期的时候才会调用Session_End)
    62         protected void Session_End(object sender, EventArgs e)
    63         {
    64             File.AppendAllText("d:\1.txt", DateTime.Now + "Session_End
    ");
    65         }
    66  
    67         protected void Application_End(object sender, EventArgs e)
    68         {
    69             File.AppendAllText("d:\1.txt", DateTime.Now + "Application_End
    ");
    70         }
    71     }
    72 }
    View Code

    UrlRewrite

     
     1 //当一个请求过来的时候
     2         //html等静态文件是iis直接把文件给到浏览器,不经过asp.net引擎的处理。
     3         //所以不会调用Application_BeginRequest方法
     4         protected void Application_BeginRequest(object sender, EventArgs e)
     5         {
     6             //即使用户访问一个不存在的页面,那么Application_BeginRequest也会被调用
     7  
     8             File.AppendAllText("d:\1.txt", DateTime.Now + "Application_BeginRequest:"+
     9                 Context.Request.RawUrl + "
    ");
    10             //Context.RewritePath("WebExcel.html");//请求重写在服务器内部发生
    11             //File.AppendAllText("d:\1.txt", DateTime.Now + "Context.Request.Path:" +
    12                 //Context.Request.Path + "
    ");
    13  
    14             int? count =(int?)Application.Get("Count");
    15             if (count == null)
    16             {
    17                 count = 1;
    18             }
    19             count++;
    20             Application.Lock();
    21             Application.Set("Count", count);
    22             Application.UnLock();
    23  
    24             //Url重写:UrlRewrite。ViewPerson-1.aspx
    25             Match match = Regex.Match(Context.Request.Path, @"^/ViewPerson-(d+).aspx$");
    26             if (match.Success)
    27             {
    28                string id = match.Groups[1].Value;
    29                Context.RewritePath("/ViewPerson.aspx?id="+id);
    30             }
    31         }

     Application

    Application是应用全局对象,被全体共享。操作之前先Lock,操作完成后UnLock。
    做网站开发尽量不要用Application,也很少有需要用它的时候。

    ASP.Net缓存

    把数据放到Cache中,在指定的时间内,可以直接从Cache中获取,避免对数据库等的压力。
    设置: HttpRuntime.Cache.Insert(CacheKey, objObject,null,absoluteExpiration,slidingExpiration);
     1 //Cache是全局共享的
     2             DataTable dt = (DataTable)HttpRuntime.Cache["persons"];
     3             if (dt == null)//如果Cache中没有,再去数据库中查询
     4                 //这样可以降低数据库服务器的压力
     5             {
     6                 dt = SqlHelper.ExecuteQuery("select * from T_Persons");
     7 
     8                 //存储缓存,30秒后过期
     9                 HttpRuntime.Cache.Insert("persons", dt, null,
    10                     DateTime.Now.AddSeconds(30), TimeSpan.Zero);
    11             }
    12             
    13             Repeater1.DataSource = dt;
    14             Repeater1.DataBind();

    母版页(*)和shtml

    Webform的母版页(MasterPage),使用母版页的窗体。母版页太笨重。
    母版页使用ContentPlaceHolder挖坑,“使用母版页的窗体”用Content填坑
    Shtml:ServerSideInclude(SSI),主流web服务器(iis、apache等)都支持。效率高,不需要经过asp.net处理,轻量级。<!--#include file="info.htm"-->
    1 <!--#include file="head.html"-->
    2 正文
    3 <!--#include file="foot.html"-->

     IIS配置

    IIS配置文档:

    1、安装IIS。控制面板→程序→打开关闭Windows功能,Web管理服务和万维网服务都勾上。

    2、部署网站:ASP.Net项目的发布:项目中点右键“发布”,选择“文件系统”,发布到一个文件夹下。

    3、在IIS中新建网站,设定域名,这样多个域名可以放到一个IIS服务器上。需要绑定域名。

    4、模拟域名,如果启用了UAC,则用管理员权限运行记事本,打开

    C:WindowsSystem32driversetc下的hosts文件

    做一下域名协议的欺骗。伪造一些域名出来。

    5、如果报错报错“无法识别的属性“targetFramework”,则:

    1)、把网站的应用程序池的.net framework版本改成“4.0” 

    2)、C:WindowsMicrosoft.NETFrameworkv4.0.30319下用管理员权限运行( aspnet_regiis.exe -i )

    6、默认文档问题,让用户访问www.web2.com的时候其实是访问www.web2.com/index.apsx:如果用户没有指定要访问哪个文件,则从上向下,匹配到谁,谁就是默认文档。

    7、MSSQL的Windows身份登录在IIS运行的问题。IIS是以Windows服务( Windows服务的特点是:系统不登录的时候已经在运行)的形式运行,由于Windows服务默认不是用当前用户名运行的,那么IIS也就不是用当前用户名运行的,那么IIS的中运行的程序也不是以当前用户名运行的,因此asp.net程序运行所采用的用户名不是SQLServer的管理员用户,因此无法用“集成身份验证”登陆SQLServer,只能用“用户名密码方式登陆”

  • 相关阅读:
    洛谷 P2048 [NOI2010]超级钢琴(优先队列,RMQ)
    洛谷P1074 靶形数独(跳舞链)
    洛谷P1337 [JSOI2004]平衡点 / 吊打XXX(模拟退火)
    洛谷P4003 无限之环(费用流)
    洛谷P3264 [JLOI2015]管道连接(斯坦纳树)
    洛谷P3190 [HNOI2007]神奇游乐园(插头dp)
    洛谷P3272 [SCOI2011]地板(插头dp)
    常用的端口配置
    Win7+Eclipse+Hadoop2.6.4开发环境搭建
    Windows10+eclipse+hadoop2.7.1环境配置+wordcount-折腾笔记
  • 原文地址:https://www.cnblogs.com/Tan-sir/p/4742250.html
Copyright © 2011-2022 走看看