您的位置:首页 > 编程语言 > ASP

ASP.Net零碎

2015-08-20 20:14 513 查看

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。

namespace Web1
{
public class Global : System.Web.HttpApplication
{
//自从服务器启动起来,网站第一次被访问的时候Application_Start执行
protected void Application_Start(object sender, EventArgs e)
{
File.AppendAllText("d:\\1.txt", DateTime.Now+"Application_Start\r\n");
}

//Session启动时
protected void Session_Start(object sender, EventArgs e)
{
File.AppendAllText("d:\\1.txt", DateTime.Now + "Session_Start\r\n");
}

//当一个请求过来的时候
//html等静态文件是iis直接把文件给到浏览器,不经过asp.net引擎的处理。
//所以不会调用Application_BeginRequest方法
protected void Application_BeginRequest(object sender, EventArgs e)
{
//即使用户访问一个不存在的页面,那么Application_BeginRequest也会被调用

File.AppendAllText("d:\\1.txt", DateTime.Now + "Application_BeginRequest:"+
Context.Request.RawUrl + "\r\n");
//Context.RewritePath("WebExcel.html");//请求重写在服务器内部发生
//File.AppendAllText("d:\\1.txt", DateTime.Now + "Context.Request.Path:" +
//Context.Request.Path + "\r\n");

int? count =(int?)Application.Get("Count");
if (count == null)
{
count = 1;
}
count++;
Application.Lock();
Application.Set("Count", count);
Application.UnLock();

//Url重写:UrlRewrite。ViewPerson-1.aspx
Match match = Regex.Match(Context.Request.Path, @"^/ViewPerson\-(\d+)\.aspx$");
if (match.Success)
{
string id = match.Groups[1].Value;
Context.RewritePath("/ViewPerson.aspx?id="+id);
}
}

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{

}

//程序中发生未处理异常
protected void Application_Error(object sender, EventArgs e)
{
File.AppendAllText("d:\\1.txt", DateTime.Now + "Application_Error:"+
Context.Error + "\r\n");
}

//(*)Session过期(只有进程内Session,也就是InProc过期的时候才会调用Session_End)
protected void Session_End(object sender, EventArgs e)
{
File.AppendAllText("d:\\1.txt", DateTime.Now + "Session_End\r\n");
}

protected void Application_End(object sender, EventArgs e)
{
File.AppendAllText("d:\\1.txt", DateTime.Now + "Application_End\r\n");
}
}
}


View Code

UrlRewrite

//当一个请求过来的时候
//html等静态文件是iis直接把文件给到浏览器,不经过asp.net引擎的处理。
//所以不会调用Application_BeginRequest方法
protected void Application_BeginRequest(object sender, EventArgs e)
{
//即使用户访问一个不存在的页面,那么Application_BeginRequest也会被调用

File.AppendAllText("d:\\1.txt", DateTime.Now + "Application_BeginRequest:"+
Context.Request.RawUrl + "\r\n");
//Context.RewritePath("WebExcel.html");//请求重写在服务器内部发生
//File.AppendAllText("d:\\1.txt", DateTime.Now + "Context.Request.Path:" +
//Context.Request.Path + "\r\n");

int? count =(int?)Application.Get("Count");
if (count == null)
{
count = 1;
}
count++;
Application.Lock();
Application.Set("Count", count);
Application.UnLock();

//Url重写:UrlRewrite。ViewPerson-1.aspx
Match match = Regex.Match(Context.Request.Path, @"^/ViewPerson\-(\d+)\.aspx$");
if (match.Success)
{
string id = match.Groups[1].Value;
Context.RewritePath("/ViewPerson.aspx?id="+id);
}
}


Application

Application是应用全局对象,被全体共享。操作之前先Lock,操作完成后UnLock。

做网站开发尽量不要用Application,也很少有需要用它的时候。

ASP.Net缓存

把数据放到Cache中,在指定的时间内,可以直接从Cache中获取,避免对数据库等的压力。
设置: HttpRuntime.Cache.Insert(CacheKey, objObject,null,absoluteExpiration,slidingExpiration);

//Cache是全局共享的
DataTable dt = (DataTable)HttpRuntime.Cache["persons"];
if (dt == null)//如果Cache中没有,再去数据库中查询
//这样可以降低数据库服务器的压力
{
dt = SqlHelper.ExecuteQuery("select * from T_Persons");

//存储缓存,30秒后过期
HttpRuntime.Cache.Insert("persons", dt, null,
DateTime.Now.AddSeconds(30), TimeSpan.Zero);
}

Repeater1.DataSource = dt;
Repeater1.DataBind();


母版页(*)和shtml

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

<!--#include file="head.html"-->
正文
<!--#include file="foot.html"-->


IIS配置

IIS配置文档:

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

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

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

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

C:\Windows\System32\drivers\etc下的hosts文件

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

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

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

2)、C:\Windows\Microsoft.NET\Framework\v4.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,只能用“用户名密码方式登陆”
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: