ASP.NET中如何实现FORM验证登录

如何运用 Form 表单认证

ASP.NET 的安全认证,共有“Windows”“Form”“Passport”“None”四种验证模式。“Windows”与“None”没有起到保护的作用,不推荐使用;“Passport”我又没用过,唉……所以我只好讲讲“Form”认证了。我打算分三部分:

第一部分 —— 怎样实现From 认证;

第二部分 —— Form 认证的实战运用;

第三部分 —— 实现单点登录(Single Sign On)

第一部分 如何运用 Form 表单认证

一、     新建一个测试项目

为了更好说明,有必要新建一个测试项目(暂且为“FormTest”吧),包含三张页面足矣(Default.aspx、Login.aspx、UserInfo.aspx)。啥?有人不会新建项目,不会新增页面?你问我咋办?我看这么办好了:拖出去,打回原藉,从幼儿园学起……

二、     修改 Web.config

1、 双击项目中的Web.config(不会的、找不到的打 PP)

2、 找到下列文字 <authentication mode="Windows" /> 把它改成:

<authentication mode="Forms">

<forms loginUrl="Login.aspx" name=".ASPXAUTH"></forms>

</authentication>

3、 找到<authorization> <allow users="*" /></authorization>换成

<authorization><deny users="?"></deny></authorization>

这里没什么好说的,只要拷贝过去就行。虽说如此,但还是有人会弄错,如下:

<authentication mode="Forms">

    <forms loginUrl="Login.aspx" name=".APSX"></forms>

<deny users="?"></deny>

</authentication>

若要问是谁把 <deny users="?"></deny> 放入 <authentication> 中的,我会很荣幸地告诉你,那是 N 年前的我:<authentication> 与 <authorization> 都是以 auth 字母开头又都是以 ation 结尾,何其相似;英文单词背不下来的我以为他们是一伙的……

三、     编写 .cs 代码——登录与退出

1、 登录代码:

a、 书本上介绍的

      private void Btn_Login_Click(object sender, System.EventArgs e)

      {

        if(this.Txt_UserName.Text=="Admin" && this.Txt_Password.Text=="123456")

        {

System.Web.Security.FormsAuthentication.RedirectFromLoginPage(this.Txt_UserName.Text,false);

}

}

b、 偶找了 N 久才找到的

private void Btn_Login_Click(object sender, System.EventArgs e)

      {
        if(this.Txt_UserName.Text=="Admin" && this.Txt_Password.Text=="123456")
        {

System.Web.Security.FormsAuthentication.SetAuthCookie(this.Txt_UserName.Text,false);

Response.Redirect("Default.aspx");

}
}

以上两种都可发放验证后的 Cookie ,即通过验证,区别:

方法 a) 指验证后返回请求页面,俗称“从哪来就打哪去”。比如:用户没登录前直接在 IE 地址栏输入 http://localhost/FormTest/UserInfo.aspx ,那么该用户将看到的是 Login.aspx?ReturnUrl=UserInfo.aspx ,输入用户名与密码登录成功后,系统将根据“ReturnUrl”的值,返回相应的页面

方法 b) 则是分两步走:通过验证后就直接发放 Cookie ,跳转页面将由程序员自行指定,此方法多用于 Default.aspx 使用框架结构的系统。

2、 退出代码:

private void Btn_LogOut_Click(object sender, System.EventArgs e)
{

System.Web.Security.FormsAuthentication.SignOut();

}

四、     如何判断验证与否及获取验证后的用户信息

有的时候,在同一张页面需要判断用户是否已经登录,然后再呈现不同的布局。有人喜欢用 Session 来判断,我不反对此类做法,在此我只是想告诉大家还有一种方法,且看下面代码:

if(User.Identity.IsAuthenticated)
{

        //你已通过验证,知道该怎么做了吧?

}

User.Identity 还有两个属性AuthenticationType(验证类型)与 Name(用户名称) ,大家要注意的是 Name 属性,此处的User.Identity.Name将得到,验证通过(RedirectFromLoginPage 或SetAuthCookie)时,我们带入的第一个参数 this.Txt_UserName.Text 。这个参数很重要,关系到种种……种种的情况,何出此言,且听下回分解……
灵活运用 Form 表单认证中的 deny 与 allow 及保护 .htm 等文件


第二部分 Form 认证的实战运用

 

Web.config 的作用范围

新建项目时, VS.Net 会在项目根目录建立一个内容固定的 Web.config。除了在项目根目录,你还可以在任一目录下建立 Web.config ,条件就是应用程序级别的节点只能在根目录的 Web.config 中出现。至于哪些是应用程序级别节点呢,这个问题嘛,其实我也不太清楚,呵呵。电脑不是我发明的,微软不是我创建的,C# 更不是我说了算的,神仙也有不知道的,所以我不晓得是正常的。话虽如此,只要它不报错,那就是对的。

关于 Web.config 设置的作用范围,记住以下两点:

1、 Web.config 的设置将作用于所在目录的所有文件及其子目录下的所有东东(继承:子随父姓)

2、 子目录下的 Web.config 设置将覆盖由父目录继承下来的设置(覆盖:县官不如现管)

给大家提个问题:有没有比根目录Web.config 的作用范围还大的配置文件呢?看完第三部分便知分晓。

六、     学会拒绝与巧用允许

回到我们在第一回合新建的测试项目“FormTest” ,既然要进行验证,按国际惯例,就得有用户名与密码。那,这些用户是管理员自己在数据库建好呢,还是用户注册、管理员审核好呢。只要不是一般的笨蛋,都知道选择后者。你们还别说,我公司还真有个别项目是管理员连到数据库去建帐号的,属于比较特殊的笨蛋,咱们不学他也罢,还是老老实实添加两个页面吧——注册页面(Register.aspx)与审核页面(Auditing.aspx)。

问题终于就要浮出水面啦,当你做好 Register.aspx 时,想访问它的时候突然觉得不对劲,怎么又回到了登录页面?你仔细瞧瞧网址,是不是成了:Login.aspx?ReturnUrl=Register.aspx 。怎么办,用户就是因为没有帐号才去访问注册页面的呀?(这句纯属废话,有帐号谁还跑去注册。)我时常对我的同事说:“办法是人想出来滴!!”

1、 新建一个目录 Public ,用于存放一些公用的文件,如万年历、脚本呀……

2、 在“解决方案资源管理器”中右击点击目录 Public ,新增一个 Web.config

3、 把上述 Web.config 的内容统统删除,仅留以下即可:

<?xml version="1.0" encoding="utf-8"?>

<configuration>

<system.web>

<authorization><allow users="*"/></authorization>

</system.web>

</configuration>

终于切入正题了,不容易呀。根据“覆盖”原则,我们知道上述 Web.config 将替代根目录 Web.config 中的 <authorization> 节点设置,即:

    <allow users="*"/> 替换 <deny users="?"></deny>

注解:“allow”允许的意思;“*”表示所有用户;

    “deny” 拒绝的意思;“?”表示匿名用户;

因此,处于 Public 目录下的文件,允许所有人浏览,包括未验证的用户。把 Register.aspx 拖进来吧,再也不会有人阻止你浏览啦。

除了注册页面,我们还提到一个审核页面(Auditing.aspx),审核权限一般都在管理员或主管手里,并不想让其他人浏览此页面(真理往往掌握在少数人的手里,这也是没法子的事),怎么办?“办法是人想出来滴”呵呵……新建一个管理员的目录 ManageSys ,在此目录下再新增一个 Web.config。内容如下:

<?xml version="1.0" encoding="utf-8"?>

<configuration>

<system.web>

<authorization>

<allow users="Admin"/>

<deny users="*"/>

</authorization>

</system.web>

</configuration>

 

System.Web.Security.FormsAuthentication.SetAuthCookie(this.Txt_UserName.Text,false); //通过验证,发放 Cookie

之前我曾强调,要注意,第一个参数很重要,重要到什么程度?说到这,恐怕地球人都知道了——它就是allow与deny的依据。假如此处用户填写的是“Admin”即 this.Txt_UserName.Text = "Admin"; 那么进入系统后,他就能访问 ManageSys 目录下的网页了,其它闲杂人等一律拒之门外。


以上 from
http://www.rjjd.com/bbs/simple/index.php?t17819.html


1: 在web.config中,加入form认证;

    <authentication mode="Forms">
   <forms name="auth" loginUrl="index.aspx" timeout="30"></forms>
</authentication>
<authorization>
   <deny users="?" />
</authorization>
2: 如果有注册页面时还应该允许匿名用户调用注册页面进行注册;
以下代码应该在<configuration><system.web>之间,而不应该包含到<system.web>..</system.web>之间;
----------------表示允许 匿名用户对 userReg.aspx页面进行访问.
<location path="userReg.aspx">
   <system.web>
    <authorization>
     <allow users="?" />
    </authorization>
   </system.web>
</location>
3 在登录成功后要 创建身份验证票, 表明已经通过认证的合法用户;

if(登陆成功)

System.Web.Security.FormsAuthentication.SetAuthCookie(用户名称, false);


1.使用Forms验证存储用户自定义信息

Forms验证在内部的机制为把用户数据加密后保存在一个基于cookie的票据FormsAuthenticationTicket中,因为是经过特殊加密的,所以应该来说是比较安全的。而.net除了用这个票据存放自己的信息外,还留了一个地给用户自由支配,这就是现在要说的UserData。

UserData可以用来存储string类型的信息,并且也享受Forms验证提供的加密保护,当我们需要这些信息时,也可以通过简单的get方法得到,兼顾了安全性和易用性,用来保存一些必须的敏感信息还是很有用的。

下面来看怎么使用UserData,然后会给出一个实际使用的例子。

//创建一个新的票据,将客户ip记入ticket的userdata
FormsAuthenticationTicket ticket=new FormsAuthenticationTicket(
1,userName.Text,DateTime.Now,DateTime.Now.AddMinutes(30),
false,Request.UserHostAddress);
//将票据加密
string authTicket=FormsAuthentication.Encrypt(ticket);
//将加密后的票据保存为cookie
HttpCookie coo=new HttpCookie(FormsAuthentication.FormsCookieName,authTicket);
//使用加入了userdata的新cookie
Response.Cookies.Add(coo);

下面是FormsAuthenticationTicket构造函数的重载之一的方法签名
public FormsAuthenticationTicket(
int version,
string name,
DateTime issueDate,
DateTime expiration,
bool isPersistent,
string userData
);

参数
version
版本号。
name
与身份验证票关联的用户名。
issueDate
Cookie 的发出时间。
expiration
Cookie 的到期日期。
isPersistent
如果 Cookie 是持久的,为 true;否则为 false。
userData
将存储在 Cookie 中的用户定义数据

使用userdata也很简单,FormsIdentity的Ticket属性就提供了对当前票据的访问,获得票据后就可以用UserData属性访问保存的信息,当然是经过解密的。
((System.Web.Security.FormsIdentity)this.Context.User.Identity).Ticket.UserData


下面是一个具体的应用。

由于Forms验证是通过cookie来进行的,它需要传递一个票据来进行工作。虽然票据是加密的,里面的内容不可见,但这并不能阻止别人用一个假冒的身份使用票据(就像我们可以拿别人的钥匙去开别人的锁),比较常见的就是不同ip的用户在不安全通道截获了这个票据,然后使用它进行一些安全范围外的活动。

解决这个问题的办法之一就是使用SSL来传递信息。

但是如果不能使用SSL呢?我们可以判断ip和票据是否匹配,如果发出请求的ip是初次产生票据的ip,则没有问题,否则就销毁这个票据。

为此,我们需要在一开始处理登录时将用户的ip保存起来,这样就可以在以后的请求中随时验证后继请求的ip是否和初始ip相同。保存这个敏感ip的最佳场所当然是UserData啦,而验证的时机则是在AuthenticateRequest事件发生时,即Global.aspx.cs中定义的处理此事件的Application_AuthenticateRequest方法中。

上面的示例实际上已经是把用户ip保存到了UserData中,下面是验证的过程。

if(this.Request.IsAuthenticated)
{
if(((System.Web.Security.FormsIdentity)this.Context.User.Identity).Ticket.UserData !=this.Request.UserHostAddress)
{
System.Security.Principal.GenericIdentity gi=new System.Security.Principal.GenericIdentity("","");
string[] rolesi={};
System.Security.Principal.GenericPrincipal gpi=new System.Security.Principal.GenericPrincipal(gi,rolesi);
this.Context.User=gpi;
}
}

通过给GenericPrincipal空的GenericIdentity和roles使票据失效,这样将强迫用户重新登录。为了测试这个方法,可以先把条件改为相等,看效果如何 :)

这个方法也有不足之处,具体为:

1.使用同一代理的用户将拥有同一个ip,这样就不能防范此类假冒攻击了

2.如果用户使用动态ip,则可能造成正常用户被我们强行销毁票据。不过总的来说,这个办法还是比较可行的。


2.使用安全特性配合Forms验证进行安全操作。

PrincipalPermissionAttribute可以配合Forms验证进行基于角色或用户的安全验证,该特性不能用于程序集级别。它的作用范围可以是类或具体的方法。来看一个简单的示例。

[PrincipalPermission(SecurityAction.Demand,User="Notus")]
public class Test : BasePage
{
private void Page_Load(object sender, System.EventArgs e)
{
try
{
this.sayHello();
this.sayHello2();
}
catch(Exception ex)
{
Response.Write(ex.ToString());
}
}

private void sayHello()
{
Response.Write("hello world!");
}

private void sayHello2()
{
Response.Write("hello PrincipalPermissionAttribute!");
}

 

#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion

}


注意这个例子一开始是作用于整个类的,生成后执行,如果当前用户不是Notus,就会发生异常System.Security.SecurityException,提示对主体权限的请求失败。反之,则可以顺利访问,并输出两个hello world!,注意是两个。现在的安全作用范围是整个类。

接下来我们改一下特性的作用范围。将特性声明移到sayHello2方法上面,重新编译后运行,就会发现程序在运行到sayHello2方法后抛出了System.Security.SecurityException。这说明现在安全作用范围缩小到了方法级别。

该特性可以通过设置User和Role来进行基于用户和角色的安全保护。另外其使用的第一个参数是SecurityAction枚举,该枚举设置了具体的保护级别或措施。像我们现在使用的这个Demand,是要求调用堆栈中的所有高级调用方都已被授予了当前权限对象所指定的权限。

下面是msdn给的示例

示例

下面的示例说明可以如何以声明方式使用 PrincipalPermission 要求当前用户是 Bob 并且属于 Supervisor 角色。
[PrincipalPermissionAttribute(SecurityAction.Demand, Name="Bob",
Role="Supervisor")]下面的示例说明如何要求当前用户的身份是 Bob,与角色成员条件无关。
[PrincipalPermissionAttribute(SecurityAction.Demand, Name="Bob")]
下面的示例说明如何仅要求对用户进行身份验证。
[PrincipalPermissionAttribute(SecurityAction.Demand, Authenticated=true)]

再要说一下的是,这里面的User和Role是可以和Forms验证集成的,据此,我们可以在一些重要的类或方法中使用PrincipalPermissionAttribute,以将自己的程序武装到家。

而实际上,该特性的作用远不止这些,更详细的信息可以查阅msdn。


或者:
1.配置Web.Config文件

设置为Form认证:
<authentication mode="Forms">
      <forms name="oursnet" loginUrl="login.aspx" timeout="10" />
</authentication>
其中:
        name:        决定验证用户时所使用的Cookie名称
        loginurl:     在用户没有登录是,被重定向的页面
        timeout:     超时时间,单位为分钟

不允许匿名登录
<authorization>
         <!-- 允许所有用户 -->
<deny users="?" />
            <!-- <allow     users="[逗号分隔的用户列表]"
                             roles="[逗号分隔的角色列表]"/>
                  <deny      users="[逗号分隔的用户列表]"
                             roles="[逗号分隔的角色列表]"/>
            -->
</authorization>
其中:
        users:    表示禁止访问资源的用户列表,使用通配符“?“拒绝匿名用户访问,使用"*",则表示拒绝所有的用户访问.

2.添加登录成功的代码:

    Session.Contents["UserName"]=txtUser.Text;
    FormsAuthentication.RedirectFromLoginPage(txtUser.Text,false);
    Response.Redirect("index.aspx");

3.添加退出时的代码
   System.Web.Security.FormsAuthentication.SignOut();
   Response.Redirect("login.aspx");

其实在ASP.Net编程中加密数据。在DotNet中有自带的类:System.Web.Security.HashPasswordForStoringInConfigFile()

public string md5(string str,int code)
{
if(code==16) //16位MD5加密(取32位加密的9~25字符)
{
return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str,"MD5").ToLower().Substring(8,16) ;
}

if(code==32) //32位加密
{
return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str,"MD5").ToLower();
}

return "00000000000000000000000000000000";
}

简单的使用:
//--导入所需要的包
using System.IO;
using System.Text;
using System.Security.Cryptography;
(1)MD5普通加密
//获取要加密的字段,并转化为Byte[]数组
byte[] data = System.Text.Encoding.Unicode
.GetBytes(TextBox1.Text.ToCharArray());
//建立加密服务
System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
//加密Byte[]数组
byte[] result = md5.ComputeHash(data);
Label1.Text = "MD5普通加密:" + System.Text.Encoding.Unicode.GetString(result);
(2)MD5密码加密[常用]
Label1.Text = "MD5密码加密:" + System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(TextBox1.Text, "MD5");

(3)ASP.NET中加密与解密QueryString的方法[常用]
//加密
Response.Redirect("DetailInfo.aspx?id=" + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes("whaben")).Replace("+","%2B"));

//解密
string ID = System.Text.Encoding.Default.GetString(Convert.FromBase64String(Request.QueryString["id"].ToString().Replace("%2B","+")));

二、DES加密及解密的算法[常用密钥算法]

简单的使用:
//--导入所需要的包
using System.IO;
using System.Text;
using System.Security.Cryptography;
public static string Key = "DKMAB5DE";//加密密钥必须为8位
//加密算法
public static string MD5Encrypt(string pToEncrypt)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
des.Key = ASCIIEncoding.ASCII.GetBytes(Key);
des.IV = ASCIIEncoding.ASCII.GetBytes(Key);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
StringBuilder ret = new StringBuilder();
foreach (byte b in ms.ToArray())
{
ret.AppendFormat("{0:X2}", b);
}
ret.ToString();
return ret.ToString();

}


//解密算法
public static string MD5Decrypt(string pToDecrypt)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
for (int x = 0; x < pToDecrypt.Length / 2; x++)
{
int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
inputByteArray[x] = (byte)i;
}
des.Key = ASCIIEncoding.ASCII.GetBytes(Key);
des.IV = ASCIIEncoding.ASCII.GetBytes(Key);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
StringBuilder ret = new StringBuilder();
return System.Text.Encoding.ASCII.GetString(ms.ToArray());

}

三、RSA加密及解密的算法[常用密钥算法]
简单的使用:
//--导入所需要的包
using System.Text;
using System.Security.Cryptography;
//加密算法
public string RSAEncrypt(string encryptString)
{
CspParameters csp = new CspParameters();
csp.KeyContainerName = "whaben";
RSACryptoServiceProvider RSAProvider = new RSACryptoServiceProvider(csp);
byte[] encryptBytes = RSAProvider.Encrypt(ASCIIEncoding.ASCII.GetBytes(encryptString), true);
string str = "";
foreach (byte b in encryptBytes)
{
str = str + string.Format("{0:x2}", b);
}
return str;
}
//解密算法
public string RSADecrypt(string decryptString)
{
CspParameters csp = new CspParameters();
csp.KeyContainerName = "whaben";
RSACryptoServiceProvider RSAProvider = new RSACryptoServiceProvider(csp);
int length = (decryptString.Length / 2);
byte[] decryptBytes = new byte[length];
for (int index = 0; index < length; index++)
{
string substring = decryptString.Substring(index * 2, 2);
decryptBytes[index] = Convert.ToByte(substring, 16);
}
decryptBytes = RSAProvider.Decrypt(decryptBytes, true);
return ASCIIEncoding.ASCII.GetString(decryptBytes);
}

1.//弹出对话框.点击转向指定页面
Response.Write("<script>window.alert('该会员没有提交申请,请重新提交!')</script>");
Response.Write("<script>window.location ='http://www.cgy.cn/bizpulic/upmeb.aspx'</script>");

2.//弹出对话框

Response.Write("<script language='javascript'>alert('产品添加成功!')</script >");

3.//删除文件


string filename ="20059595157517.jpg";
pub.util.DeleteFile(HttpContext.Current.Server.MapPath("../file/")+filename);

4.//绑定下拉列表框datalist

System.Data.DataView dv=conn.Exec_ex("select -1 as code,'请选择经营模式' as content from dealin union select code,content from dealin");
this.dealincode.DataSource=dv;
this.dealincode.DataTextField="content";
this.dealincode.DataValueField="code";  
this.dealincode.DataBind();
this.dealincode.Items.FindByValue(dv[0]["dealincode"].ToString()).Selected=true;

5.//时间去秒显示

<%# System.DateTime.Parse(DataBinder.Eval(Container.DataItem,"begtime").ToString()).ToShortDateString()%>

6.//标题带链接

<%# "<a class=\"12c\" target=\"_blank\" href=\"http://www.51aspx/CV/_"+DataBinder.Eval(Container.DataItem,"procode")+".html\">"+ DataBinder.Eval(Container.DataItem,"proname")+"</a>"%>


7.//修改转向

<%# "<A href=\"editpushpro.aspx?id="+DataBinder.Eval(Container.DataItem,"code")+"\">"+"修改"+"</A>"%>


8.//弹出确定按钮

<%# "<A id=\"btnDelete\" onclick=\"return confirm('你是否确定删除这条记录吗?');\" href=\"pushproduct.aspx?dl="+DataBinder.Eval(Container.DataItem,"code")+"\">"+"删除"+"</A>"%>


9.//输出数据格式化 "{0:F2}" 是格式 F2表示小数点后剩两位

<%# DataBinder.Eval(Container, "DataItem.PriceMoney","{0:F2}") %>

10.//提取动态网页内容

Uri uri = new Uri("http://www.soAsp.net/");
WebRequest req = WebRequest.Create(uri);
WebResponse resp = req.GetResponse();
Stream str = resp.GetResponseStream();
StreamReader sr = new StreamReader(str,System.Text.Encoding.Default);
string t = sr.ReadToEnd();
this.Response.Write(t.ToString());

11.//获取" . "后面的字符

i.ToString().Trim().Substring(i.ToString().Trim().LastIndexOf(".")+1).ToLower().Trim()

12. 打开新的窗口并传送参数:
  传送参数:

response.write("<script>window.open(’*.aspx?id="+this.DropDownList1.SelectIndex+"&id1="+...+"’)</script>")

接收参数:

string a = Request.QueryString("id");
string b = Request.QueryString("id1");

12.为按钮添加对话框

Button1.Attributes.Add("onclick","return confirm(’确认?’)");
button.attributes.add("onclick","if(confirm(’are you sure...?’)){return true;}else{return false;}")

13.删除表格选定记录

int intEmpID = (int)MyDataGrid.DataKeys[e.Item.ItemIndex];
string deleteCmd = "Delete from Employee where emp_id = " + intEmpID.ToString()

14.删除表格记录警告

private void DataGrid_ItemCreated(Object sender,DataGridItemEventArgs e)
{
  switch(e.Item.ItemType)
  {
  case ListItemType.Item :
  case ListItemType.AlternatingItem :
  case ListItemType.EditItem:
  TableCell myTableCell;
  myTableCell = e.Item.Cells[14];
  LinkButton myDeleteButton ;
  myDeleteButton = (LinkButton)myTableCell.Controls[0];
  myDeleteButton.Attributes.Add("onclick","return confirm(’您是否确定要删除这条信息’);");
  break;
  default:
  break;
  }
}

15.点击表格行链接另一页

private void grdCustomer_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
  //点击表格打开
  if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
  e.Item.Attributes.Add("onclick","window.open(’Default.aspx?id=" + e.Item.Cells[0].Text + "’);");
}

双击表格连接到另一页
  在itemDataBind事件中

if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
  string orderItemID =e.item.cells[1].Text;
  e.item.Attributes.Add("ondblclick", "location.href=’../ShippedGrid.aspx?id=" + orderItemID + "’");
}

双击表格打开新一页

if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
  string orderItemID =e.item.cells[1].Text;
  e.item.Attributes.Add("ondblclick", "open(’../ShippedGrid.aspx?id=" + orderItemID + "’)");
}


16.表格超连接列传递参数

<asp:HyperLinkColumn Target="_blank" headertext="ID号" DataTextField="id" NavigateUrl="aaa.aspx?id=’
  <%# DataBinder.Eval(Container.DataItem, "数据字段1")%>’ & name=’<%# DataBinder.Eval(Container.DataItem, "数据字段2")%>’ />

17.表格点击改变颜色

if (e.Item.ItemType == ListItemType.Item ||e.Item.ItemType == ListItemType.AlternatingItem)
{
  e.Item.Attributes.Add("onclick","this.style.backgroundColor=’#99cc00’;
    this.style.color=’buttontext’;this.style.cursor=’default’;");
}

写在DataGrid的_ItemDataBound里

if (e.Item.ItemType == ListItemType.Item ||e.Item.ItemType == ListItemType.AlternatingItem)
{
e.Item.Attributes.Add("onmouseover","this.style.backgroundColor=’#99cc00’;
  this.style.color=’buttontext’;this.style.cursor=’default’;");
e.Item.Attributes.Add("onmouseout","this.style.backgroundColor=’’;this.style.color=’’;");
}

18.关于日期格式
  日期格式设定
DataFormatString="{0:yyyy-MM-dd}"
  我觉得应该在itembound事件中
e.items.cell["你的列"].text=DateTime.Parse(e.items.cell["你的列"].text.ToString("yyyy-MM-dd"))
19.获取错误信息并到指定页面
不要使用Response.Redirect,而应该使用Server.Transfer
  e.g

// in global.asax
protected void Application_Error(Object sender, EventArgs e) {
if (Server.GetLastError() is HttpUnhandledException)
Server.Transfer("MyErrorPage.aspx");


//其余的非HttpUnhandledException异常交给ASP.NET自己处理就okay了 :)
}
  Redirect会导致post-back的产生从而丢失了错误信息,所以页面导向应该直接在服务器端执行,这样就可以在错误处理页面得到出错信息并进行相应的处理
20.清空Cookie

Cookie.Expires=[DateTime];
Response.Cookies("UserName").Expires = 0

21.自定义异常处理

//自定义异常处理类
using System;
using System.Diagnostics;
namespace MyAppException
{
  /// <summary>
  /// 从系统异常类ApplicationException继承的应用程序异常处理类。
  /// 自动将异常内容记录到Windows NT/2000的应用程序日志
  /// </summary>
  public class AppException:System.ApplicationException
  {
  public AppException()
  {
  if (ApplicationConfiguration.EventLogEnabled)LogEvent("出现一个未知错误。");
  }
  public AppException(string message)
  {
  LogEvent(message);
  }
  public AppException(string message,Exception innerException)
  {
  LogEvent(message);
  if (innerException != null)
  {
  LogEvent(innerException.Message);
  }
  }
  //日志记录类
  using System;
  using System.Configuration;
  using System.Diagnostics;
  using System.IO;
  using System.Text;
  using System.Threading;
  namespace MyEventLog
  {
  /// <summary>
  /// 事件日志记录类,提供事件日志记录支持
  /// <remarks>
  /// 定义了4个日志记录方法 (error, warning, info, trace)
  /// </remarks>
  /// </summary>
  public class ApplicationLog
  {
  /// <summary>
  /// 将错误信息记录到Win2000/NT事件日志中
  /// <param name="message">需要记录的文本信息</param>
  /// </summary>
  public static void WriteError(String message)
  {
  WriteLog(TraceLevel.Error, message);
  }
  /// <summary>
  /// 将警告信息记录到Win2000/NT事件日志中
  /// <param name="message">需要记录的文本信息</param>
  /// </summary>
  public static void WriteWarning(String message)
  {
  WriteLog(TraceLevel.Warning, message);  
  }
  /// <summary>
  /// 将提示信息记录到Win2000/NT事件日志中
  /// <param name="message">需要记录的文本信息</param>
  /// </summary>
  public static void WriteInfo(String message)
  {
  WriteLog(TraceLevel.Info, message);
  }
  /// <summary>
  /// 将跟踪信息记录到Win2000/NT事件日志中
  /// <param name="message">需要记录的文本信息</param>
  /// </summary>
  public static void WriteTrace(String message)
  {
  WriteLog(TraceLevel.Verbose, message);
  }
  /// <summary>
  /// 格式化记录到事件日志的文本信息格式
  /// <param name="ex">需要格式化的异常对象</param>
  /// <param name="catchInfo">异常信息标题字符串.</param>
  /// <retvalue>
  /// <para>格式后的异常信息字符串,包括异常内容和跟踪堆栈.</para>
  /// </retvalue>
  /// </summary>
  public static String FormatException(Exception ex, String catchInfo)
  {
  StringBuilder strBuilder = new StringBuilder();
  if (catchInfo != String.Empty)
  {
  strBuilder.Append(catchInfo).Append("\r\n");
  }
  strBuilder.Append(ex.Message).Append("\r\n").Append(ex.StackTrace);
  return strBuilder.ToString();
  }
  /// <summary>
  /// 实际事件日志写入方法
  /// <param name="level">要记录信息的级别(error,warning,info,trace).</param>
  /// <param name="messageText">要记录的文本.</param>
  /// </summary>
  private static void WriteLog(TraceLevel level, String messageText)
  {
  try
  {
  EventLogEntryType LogEntryType;
  switch (level)
  {
  case TraceLevel.Error:
  LogEntryType = EventLogEntryType.Error;
  break;
  case TraceLevel.Warning:
  LogEntryType = EventLogEntryType.Warning;
  break;
  case TraceLevel.Info:
  LogEntryType = EventLogEntryType.Information;
  break;
  case TraceLevel.Verbose:
  LogEntryType = EventLogEntryType.SuccessAudit;
  break;
  default:
  LogEntryType = EventLogEntryType.SuccessAudit;
  break;
  }
  EventLog eventLog = new EventLog("Application", ApplicationConfiguration.EventLogMachineName, ApplicationConfiguration.EventLogSourceName );
  //写入事件日志
  eventLog.WriteEntry(messageText, LogEntryType);
  }
  catch {} //忽略任何异常
  }
  } //class ApplicationLog
}

22.Panel 横向滚动,纵向自动扩展

<asp:panel style="overflow-x:scroll;overflow-y:auto;"></asp:panel>

23.回车转换成Tab
(1)


<script language="javascript" for="document" event="onkeydown">
  if(event.keyCode==13 && event.srcElement.type!=’button’ && event.srcElement.type!=’submit’ &&     event.srcElement.type!=’reset’ && event.srcElement.type!=’’&& event.srcElement.type!=’textarea’);
  event.keyCode=9;
</script>

(2) //当在有keydown事件的控件上敲回车时,变为tab

public void Tab(System.Web .UI.WebControls .WebControl webcontrol)
{
webcontrol.Attributes .Add ("onkeydown", "if(event.keyCode==13) event.keyCode=9");
}
24.DataGrid超级连接列
DataNavigateUrlField="字段名" DataNavigateUrlFormatString="http://xx/inc/delete.aspx?ID={0}"

25.DataGrid行随鼠标变色

private void DGzf_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
  if (e.Item.ItemType!=ListItemType.Header)
  {
  e.Item.Attributes.Add( "onmouseout","this.style.backgroundColor=\""+e.Item.Style["BACKGROUND-COLOR"]+"\"");
  e.Item.Attributes.Add( "onmouseover","this.style.backgroundColor=\""+ "#EFF3F7"+"\"");
  }
}

26.模板列

<ASP:TEMPLATECOLUMN visible="False" sortexpression="demo" headertext="ID">
<ITEMTEMPLATE>
<ASP LABEL text=’<%# DataBinder.Eval(Container.DataItem, "ArticleID")%>’ runat="server" width="80%" id="lblColumn" />
</ITEMTEMPLATE>
</ASP:TEMPLATECOLUMN>
<ASP:TEMPLATECOLUMN headertext="选中">
<HEADERSTYLE wrap="False" horiz></HEADERSTYLE>
<ITEMTEMPLATE>
<ASP:CHECKBOX id="chkExport" runat="server" />
</ITEMTEMPLATE>
<EDITITEMTEMPLATE>
<ASP:CHECKBOX id="chkExportON" runat="server" enabled="true" />
</EDITITEMTEMPLATE>
</ASP:TEMPLATECOLUMN>

后台代码

protected void CheckAll_CheckedChanged(object sender, System.EventArgs e)
{
  //改变列的选定,实现全选或全不选。
  CheckBox chkExport ;
  if( CheckAll.Checked)
  {
  foreach(DataGridItem oDataGridItem in MyDataGrid.Items)
  {
  chkExport = (CheckBox)oDataGridItem.FindControl("chkExport");
  chkExport.Checked = true;
  }
  }
  else
  {
  foreach(DataGridItem oDataGridItem in MyDataGrid.Items)
  {
  chkExport = (CheckBox)oDataGridItem.FindControl("chkExport");
  chkExport.Checked = false;
  }
  }
}

27.数字格式化


【<%#Container.DataItem("price")%>的结果是500.0000,怎样格式化为500.00?】
<%#Container.DataItem("price","{0:¥#,##0.00}")%>
int i=123456;
string s=i.ToString("###,###.00");

28.日期格式化
  【aspx页面内:<%# DataBinder.Eval(Container.DataItem,"Company_Ureg_Date")%>
  显示为: 2004-8-11 19:44:28
  我只想要:2004-8-11 】
<%# DataBinder.Eval(Container.DataItem,"Company_Ureg_Date","{0:yyyy-M-d}")%>
  应该如何改?
  【格式化日期】
  取出来,一般是object((DateTime)objectFromDB).ToString("yyyy-MM-dd");
  【日期的验证表达式】
  A.以下正确的输入格式: [2004-2-29], [2004-02-29 10:29:39 pm], [2004/12/31]
^((\d{2}(([02468][048])|([13579][26]))[\-\/\s]?((((0?[13578])|(1[02]))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|([1-2][0-9])))))|(\d{2}(([02468][1235679])|([13579][01345789]))[\-\/\s]?((((0?[13578])|(1[02]))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\s(((0?[1-9])|(1[0-2]))\:([0-5][0-9])((\s)|(\:([0-5][0-9])\s))([AM|PM|am|pm]{2,2})))?$
  B.以下正确的输入格式:[0001-12-31], [9999 09 30], [2002/03/03]
^\d{4}[\-\/\s]?((((0[13578])|(1[02]))[\-\/\s]?(([0-2][0-9])|(3[01])))|(((0[469])|(11))[\-\/\s]?(([0-2][0-9])|(30)))|(02[\-\/\s]?[0-2][0-9]))$
  【大小写转换】
HttpUtility.HtmlEncode(string);
HttpUtility.HtmlDecode(string)
29.如何设定全局变量
  Global.asax中
  Application_Start()事件中
  添加Application[属性名] = xxx;
  就是你的全局变量

前台代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="aaaaaaaaa.aspx.cs" Inherits="aaaaaaaaa" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>无标题页</title>

    <script type="text/javascript">
var i=1;
function addFile()
{
    if (i<3)
    {
        var str = '<BR> <input type="file" name="File" onchange="addFile();" runat="server" style=" 300px"/>描述:<input name="text" type="text" style=" 150px" maxlength="20" />'
        document.getElementById('MyFile').insertAdjacentHTML("beforeEnd",str);
    }
    else
    {
        alert("您一次最多只能上传3张图片!");
    }
    i++;
}
    </script>

</head>
<body>
    <form id="form1" runat="server">
        <div>
            <p id="MyFile">
                <input id="File1" type="file" name="File" onchange="addFile();" runat="server" style=" 300px" />
                描述:<input name="text" type="text" style=" 150px" maxlength="20" />
            </p>
            <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
        </div>
    </form>
</body>
</html>

后台代码:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class aaaaaaaaa : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        System.Web.HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
        string[] rd = Request.Form[1].Split(',');//获得图片描述的文本框字符串数组,为对应的图片的描述
        //string albumid = ddlAlbum.SelectedValue.Trim();
        int ifile;

        for (ifile = 0; ifile < files.Count; ifile++)
        {
            if (files[ifile].FileName.Length > 0)
            {
                string aa = files[ifile].FileName.ToString();
                string bb = rd[ifile].ToString();
                //上传单个文件并保存相关信息保存到服务器自己去写了
            }
        }
    }
}

Js按比例缩放图片
<script>
<!--
//调用方式<img src='"+url+"' onload='javascript:DrawImage(this,300,380)'>

//图片按比例缩放
var flag=false;
function DrawImage(ImgD,iwidth,iheight){
     //参数(图片,允许的宽度,允许的高度)
     var image=new Image();
     image.src=ImgD.src;
     if(image.width>0 && image.height>0){
     flag=true;
     if(image.width/image.height>= iwidth/iheight){
         if(image.width>iwidth){  
         ImgD.width=iwidth;
         ImgD.height=(image.height*iwidth)/image.width;
         }else{
         ImgD.width=image.width;  
         ImgD.height=image.height;
         }
         ImgD.alt=image.width+"×"+image.height;
         }
     else{
         if(image.height>iheight){  
         ImgD.height=iheight;
         ImgD.width=(image.width*iheight)/image.height;        
         }else{
         ImgD.width=image.width;  
         ImgD.height=image.height;
         }
         ImgD.alt=image.width+"×"+image.height;
         }
     }
}
//查看已经上传得图片
function showpic(url,divname){
var obj=document.getElementById(divname);
   document.all(divname).style.display="block";
   obj.innerHTML="<img src='"+url+"' onload='javascript:DrawImage(this,300,380)'><br><a href='#' onClick='javascrpt:closeshowpic();'>关闭</a>";
}
function closeshowpic()
{
document.all("lookuppic").style.display="none";
}
//-->
</script>
<img src="http://www.baidu.com/img/logo-yy.gif" onload='javascript:DrawImage(this,100,20)' />

原文地址:https://www.cnblogs.com/Leo_wl/p/1888086.html