转web.config介绍

本文介绍了一种使用ASP.NET Forms进行用户验证的方法。通过创建数据库、配置web.config文件及实现登录页面逻辑,确保只有经过验证的用户才能访问特定资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


资料引用:

http://www.knowsky.com/343322.html

http://baike.baidu.com/view/1365881.htm

关于Forms验证的文章网上千百篇,但花了1天半的时间学会了“一点点”,
现在把代码分享出来,希望对像一样的初学者所有帮助,也希望高手给指点一下:



Step 1:新建数据库(库:MyForms ;表:users ;字段:ID,userName, userPwd);
Step 2:新建网站,web.config 的文件全部代码如下:

 

 


<?xml version="1.0"?>
<configuration>
    
<appSettings/>
    
<connectionStrings/>
  
    
<system.web>
        
<compilation debug="true"/>
    
    
<sessionState cookieless="AutoDetect"/>
    
<!--解决当浏览器端禁用Cookie时-->
    
        
<authentication mode="Forms">
      
<forms name="CookieName" loginUrl="login.aspx" protection="All"></forms>
      
<!--loginUrl为登录面URL,如果没有身份验证Cookie,客户端将被重定向到此URL-->
    
</authentication>
    
    
<authorization>
      
<deny users="?"/> 
    
</authorization>
    
    
<customErrors mode="On" defaultRedirect="GenericErrorPage.htm">
        
<error statusCode="403" redirect="NoAccess.htm" />
        
<error statusCode="404" redirect="FileNotFound.htm" />
    
</customErrors>
    
    
</system.web>
  
</configuration>


Step 3:添加一个 login.aspx  页面;拖2个 TextBox ,1个Button 和1个CheckBox ;
           并将CheckBox 的text 属性设为:“是否保存Cookis ";
Step 4:login.aspx 的隐藏代码如下:


using System;
using System.Data;
using System.Configuration;
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;
using System.Data.SqlClient; //导入命名空间

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

    }

    
protected void Button1_Click(object sender, EventArgs e)
    
{
        
string userName = TextBox1.Text.Trim();
        
string userPwd = TextBox2.Text.Trim();
        SqlConnection con 
= new SqlConnection("Server=.;Database=MyForms;User ID=sa;Password=123456");
        con.Open();
        SqlCommand cmd 
= new SqlCommand("select count(*) from users where userName='" + userName + "' and userPwd='" + userPwd + "'", con);
        
int count = Convert.ToInt32(cmd.ExecuteScalar());
        
if (count > 0)
        
{
            System.Web.Security.FormsAuthentication.SetAuthCookie(
this.TextBox1.Text, this.CheckBox1.Checked);
            Response.Redirect(
"Default.aspx");
            
//上面两行,也可以换成下面一行,如通过验证则直接转向请求的页面,而不需要Responsel.Redirect("");
            
//System.Web.Security.FormsAuthentication.RedirectFromLoginPage(this.TextBox1.Text, false);   
        }


        
else
        
{
            Response.Write(
"用户不合法");
        }
       
    }

}


资料引用:http://www.knowsky.com/343322.html

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值