按月存档: 07月 2008

Asp.Net防止刷新重复提交数据小记

最近在用Asp.Net编写点东西时遇到个问题:即用户在提交表单后按刷新就会重复提交数据,即所谓的“刷新重复提交”的问题。在网上搜 一下,可以找到很多关于这方面的资料,其中有一篇是来自MSDN上的一种解决方法: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnvs05/html/BedrockASPNET.asp 它是通过重新定义 System.Web.UI.Page 类来实现加载页面时,是“刷新”、“后退”请求,还是正常请求,其他的页面则继承了自定义的这 个Page类。感觉他这个方法比较独特,有例子可以下载,有兴趣的可以研究研究。
网上最多的解决此类问题的方法就是不保存缓存,即提交后表单上的数据不会被浏览器的缓存保存,如果此时再遇到刷新或者后退请求时, 就会显示“网页已过期”,数据也就不会重复提交了,这就起到了阻止刷新重复提交的效果。
下面以简单的提交一篇帖子为例,介绍禁用缓存防止刷新重复提交的方法,表单数据包括“标题”和“正文”两个部分。
以下是该方法的代码(post.aspx):
//页面加载
protected void Page_Load(object sender, EventArgs e)
{
   //可以在页面加载时设置页面的缓存为“SetNoStore()”,即无缓存
   Response.Cache.SetNoStore();
   //Session中存储的变量“IsSubmit”是标记是否提交成功的
   if ((bool)Session["IsSubmit"])
   {
     //如果表单数据提交成功,就设“Session["IsSubmit"]”为false
     Session["IsSubmit"] = false;
     //显示提交成功信息
     ShowMsg.Text = " * 提交成功!";
   }
   else
     //否则的话(没有提交,或者是页面刷新),不显示任何信息
     ShowMsg.Text = "";
}
//提交按钮(btnOK)单击事件
protected void btnOK_Click(object sender, EventArgs e)
{
   if (txtTitle.Text.ToString().Trim() == "")
     //ShowMsg是用来显示提示信息的
     ShowMsg.Text = " * 标题不能为空!";
  else if (txtText.Text.ToString().Trim() == "")
     ShowMsg.Text = " * 内容不能为空!";
  else
   {
     //这里是将数据提交到数据库中,省略
     /*
     string sql = "insert into tab…values(…)";
     MyConn.ExecQuery(sql);
     */
     //提交成功后,设“Session["IsSubmit"]”为true
     Session["IsSubmit"] = true;
     //强制转换页面(不可少,否则刷新仍会重复提交,仍转到本页),
     通过页面的转换将缓存中的提交的数据都释放了,即提交的标单数据不会被保存到缓存里,
     如果后退的话,将会出现该页无法显示
     Response.Redirect("post.aspx");
  }
}
上面这个方法非常简单也很实用,推荐大家使用。

asp.net获取URL和IP地址

HttpContext.Current.Request.Url.ToString() 并不可靠。

如果当前URL为 
http://localhost/search.aspx?user=http://csharp.xdowns.com&tag=%BC%BC%CA%F5 

通过HttpContext.Current.Request.Url.ToString()获取到的却是 

http://localhost/search.aspxuser=http://csharp.xdowns.com&tag=¼¼Êõ 

正确的方法是:HttpContext.Current.Request.Url.PathAndQuery
1、通过ASP.NET获取
如果测试的url地址是http://www.test.com/testweb/default.aspx, 结果如下:
Request.ApplicationPath:                /testweb
Request.CurrentExecutionFilePath:       /testweb/default.aspx
Request.FilePath:                       /testweb/default.aspx
Request.Path:                           /testweb/default.aspx
Request.PhysicalApplicationPath:        E:\WWW\testwebRequest.PhysicalPath:                   E:\WWW\testweb\default.aspx
Request.RawUrl:                         /testweb/default.aspx
Request.Url.AbsolutePath:               /testweb/default.aspx
Request.Url.AbsoluteUrl:                http://www.test.com/testweb/default.aspx
Request.Url.Host:                       www.test.com
Request.Url.LocalPath:                  /testweb/default.aspx 

2、通过JS获取

<table width=100% cellpadding=0 cellspacing=0 border=0 >

<script> 

thisURL = document.URL; 

thisHREF = document.location.href; 

thisSLoc = self.location.href; 

thisDLoc = document.location; 

strwrite = "<tr><td valign=top>thisURL: </td><td>[" + thisURL + "]</td></tr>" 

strwrite += "<tr><td valign=top>thisHREF: </td><td>[" + thisHREF + "]</td></tr>" 

strwrite += "<tr><td valign=top>thisSLoc: </td><td>[" + thisSLoc + "]</td></tr>" 

strwrite += "<tr><td valign=top>thisDLoc: </td><td>[" + thisDLoc + "]</td></tr>" 

document.write( strwrite ); 

</script> 

thisDLoc = document.location; <BR>

thisURL = document.URL; <BR>

thisHREF = document.location.href; <BR>

thisSLoc = self.location.href;<BR>

<script> 

thisTLoc = top.location.href; 

thisPLoc = parent.document.location; 

thisTHost = top.location.hostname; 

thisHost = location.hostname; 

strwrite = "<tr><td valign=top>thisTLoc: </td><td>[" + thisTLoc + "]</td></tr>" 

strwrite += "<tr><td valign=top>thisPLoc: </td><td>[" + thisPLoc + "]</td></tr>" 

strwrite += "<tr><td valign=top>thisTHost: </td><td>[" + thisTHost + "]</td></tr>" 

strwrite += "<tr><td valign=top>thisHost: </td><td>[" + thisHost + "]</td></tr>" 

document.write( strwrite ); 

</script> 

thisTLoc = top.location.href; <BR>

thisPLoc = parent.document.location; <BR>

thisTHost = top.location.hostname; <BR>

thisHost = location.hostname;<BR>

<script> 

tmpHPage = thisHREF.split( "/" ); 

thisHPage = tmpHPage[ tmpHPage.length-1 ]; 

tmpUPage = thisURL.split( "/" ); 

thisUPage = tmpUPage[ tmpUPage.length-1 ]; 

strwrite = "<tr><td valign=top>thisHPage: </td><td>[" + thisHPage + "]</td></tr>" 

strwrite += "<tr><td valign=top>thisUPage: </td><td>[" + thisUPage + "]</td></tr>" 

document.write( strwrite ); 

</script><tr><td>

=================
获取IP
1、ASP.NET中获取

获取服务器的IP地址: 
using System.Net; 

string myIP,myMac;
System.Net.IPAddress[] addressList = Dns.GetHostByName(Dns.GetHostName()).AddressList; 
if ( addressList.Length>1) 
{
 myIP = addressList[0].ToString(); 
 myMac = addressList[1].ToString(); 

else 

 myIP = addressList[0].ToString(); 
 myMac = "没有可用的连接";

myIP地址就是服务器端的ip地址。

获取客户端的ip地址,可以使用

//获取登录者ip地址
string ip = Request.ServerVariables["REMOTE_ADDR"].ToString(); 
2、通过JS获取
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=gbk">
</head>

<body>

<object classid="CLSID:76A64158-CB41-11D1-8B02-00600806D9B6" id="locator" style="display:none;visibility:hidden"></object>
<object classid="CLSID:75718C9A-F029-11d1-A1AC-00C04FB6C223" id="foo" style="display:none;visibility:hidden"></object>                                                         

<form name="myForm">
 <br/>MAC地址:<input type="text" name="macAddress">
 <br/>IP地址:<input type="text" name="ipAddress">
 <br/>主机名:<input type="text" name="hostName">
</form>

</body>
</html>
<script language="javascript">
 var sMacAddr="";
 var sIPAddr="";
 var sDNSName="";

 var service = locator.ConnectServer();
 service.Security_.ImpersonationLevel=3;
 service.InstancesOfAsync(foo, ’Win32_NetworkAdapterConfiguration’);

</script>

<script FOR="foo" EVENT="OnObjectReady(objObject,objAsyncContext)" LANGUAGE="JScript">
        if(objObject.IPEnabled != null && objObject.IPEnabled != "undefined" && objObject.IPEnabled == true){
                          if(objObject.IPEnabled && objObject.IPAddress(0) !=null && objObject.IPAddress(0) != "undefined")
                                        sIPAddr = objObject.IPAddress(0);
                          if(objObject.MACAddress != null &&objObject.MACAddress != "undefined")
                    sMacAddr = objObject.MACAddress;
                          if(objObject.DNSHostName != null &&objObject.DNSHostName != "undefined")
                                        sDNSName = objObject.DNSHostName;
         }
</script>

<script FOR="foo" EVENT="OnCompleted(hResult,pErrorObject, pAsyncContext)" LANGUAGE="JScript">

       myForm.macAddress.value=sMacAddr;
 myForm.ipAddress.value=sIPAddr;
       myForm.hostName.value=sDNSName;
</script>

TimeSpan 用法 求离最近发表时间的函数

求离最近发表时间的函数
 
public string DateStringFromNow(DateTime dt)    
{    
TimeSpan span = DateTime.Now - dt;    
if (span.TotalDays > 60)    
{    
return dt.ToShortDateString();    
}    
else if ( span.TotalDays > 30 )    
{    
return "1个月前";    
}    
else if (span.TotalDays > 14)    
{    
return "2周前";    
}    
else if (span.TotalDays > 7)    
{    
return "1周前";    
}    
else if (span.TotalDays > 1)    
{    
return string.Format("{0}天前", (int)Math.Floor(span.TotalDays));    
}    
else if (span.TotalHours > 1)    
{    
return string.Format("{0}小时前", (int)Math.Floor(span.TotalHours));    
}    
else if (span.TotalMinutes > 1)    
{    
return string.Format("{0}分钟前", (int)Math.Floor(span.TotalMinutes));    
}    
else if (span.TotalSeconds >= 1)    
{    
return string.Format("{0}秒前", (int)Math.Floor(span.TotalSeconds));    
}    
else   
{    
return "1秒前";    
}    
}    
 
C#中使用TimeSpan计算两个时间的差值
可以反加两个日期之间任何一个时间单位。
private string DateDiff(DateTime DateTime1, DateTime DateTime2)
{string dateDiff = null;
TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
TimeSpan ts = ts1.Subtract(ts2).Duration();
dateDiff = ts.Days.ToString()+"天"+ ts.Hours.ToString()+"小时"+ ts.Minutes.ToString()+"分钟"+ ts.Seconds.ToString()+"秒";
return dateDiff;
}
 
TimeSpan    ts    =    Date1    -    Date2;   
   double    dDays    =    ts.TotalDays;//带小数的天数,比如1天12小时结果就是1.5   
   int    nDays    =    ts.Days;//整数天数,1天12小时或者1天20小时结果都是1   
说明:
1.DateTime值类型代表了一个从公元0001年1月1日0点0分0秒到公元9999年12月31日23点59分59秒之间的具体日期时刻。因此,你可以用DateTime值类型来描述任何在想象范围之内的时间。一个DateTime值代表了一个具体的时刻
2.TimeSpan值包含了许多属性与方法,用于访问或处理一个TimeSpan值
下面的列表涵盖了其中的一部分:
Add:与另一个TimeSpan值相加。
Days:返回用天数计算的TimeSpan值。
Duration:获取TimeSpan的绝对值。
Hours:返回用小时计算的TimeSpan值
Milliseconds:返回用毫秒计算的TimeSpan值。
Minutes:返回用分钟计算的TimeSpan值。
Negate:返回当前实例的相反数。
Seconds:返回用秒计算的TimeSpan值。
Subtract:从中减去另一个TimeSpan值。
Ticks:返回TimeSpan值的tick数。
TotalDays:返回TimeSpan值表示的天数。
TotalHours:返回TimeSpan值表示的小时数。
TotalMilliseconds:返回TimeSpan值表示的毫秒数。
TotalMinutes:返回TimeSpan值表示的分钟数。
TotalSeconds:返回TimeSpan值表示的秒数。
 
          /// <summary>
          /// 日期比较
          /// </summary>
          /// <param name="today">当前日期</param>
          /// <param name="writeDate">输入日期</param>
          /// <param name="n">比较天数</param>
          /// <returns>大于天数返回true,小于返回false</returns>
          private bool CompareDate(string today, string writeDate, int n)
          {
              DateTime Today = Convert.ToDateTime(today);
              DateTime WriteDate = Convert.ToDateTime(writeDate);
              WriteDate = WriteDate.AddDays(n);
              if (Today >= WriteDate)
                  return false;
              else
                  return true;
          }

在Web.config中指定编码

<configuration>

<system.web>

 <globalization
requestEncoding="shift-jis"
responseEncoding="shift-jis"
fileEncoding="shift-jis" … />

</system.web>

</configuration>
 
Web 开发人员可能还想要以代码页编码保存文件。可以使用 fileEncoding 属性声明编码。