1. ホーム
  2. asp.net

asp.netのログイン画面作成例

2022-02-20 11:44:01

クラスライブラリのコードは以下の通りです。

using System;
Generic;
Linq;
Web; using System;
Data.SqlClient; using System;
SqlClient; using System;
Data;

/// <summary>
//// Summary description of CommonClass
/// </summary>
public class CommonClass
{
	public CommonClass()
	{
		
	}
    /// <summary>
    //// Database connection class
    /// </summary>
    //// <returns> connection object</returns>
    public SqlConnection GetConnection()
    {
        string myStr = ConfigurationManager.AppSettings["ConnectionString"].ToString();
        SqlConnection myConn = new SqlConnection(myStr);
        return myConn;

    }
    /// <summary>
    /// Popup box
    /// </summary>
    /// <param name="TxtMessage">Popup alert message </param>
    /// <param name="Url">Go to address after dialog is closed</param>
    /// <returns></returns>
    //// 
    public string MessageBox(string TxtMessage,string Url) {
        string str;
        str = "<script language=javascript>alert('"+TxtMessage+"');location='"+Url+"'</script>";
        return str;  
    }
    /// <summary>
    //// Used to perform add, delete and change functions
    /// </summary>
    /// <param name="sqlStr"> SQL statement for operation </param>
    /// <returns> success returns TRUE, failure returns FALSE</returns>
    //// 
    public Boolean ExecSQL(string sqlStr) {
        SqlConnection myConn = GetConnection();
        myConn.Open();

        SqlCommand myCmd = new SqlCommand(sqlStr,myConn);
        try
        {
            myCmd.ExecuteNonQuery();
            myConn.Close();

        }
        catch {
            myConn.Close();
            return false;      
        }
        return true;
    
    }
    /// <summary>
    //// Returns the dataset of the data source
    /// </summary>
    /// <param name="sqlStr">Operation SQL statement</param>
    /// <param name="TableName">Data table name</param>
    /// <returns> DataSetDataSet</returns>
    public DataSet GetDataSet(string sqlStr, string TableName) {
        SqlConnection myConn = GetConnection();
        myConn.Open();
        SqlDataAdapter adapt = new SqlDataAdapter(sqlStr, myConn);
        DataSet ds = new DataSet();
        adapt.Fill(ds, TableName);
        myConn.Close();
        return ds;
    }
    /// <summary>
    /// Verify login to prevent SQL injection attacks
    /// </summary>
    /// <param name="loginName">username</param>
    /// <param name="loginPwd">password</param>
    /// <returns></returns>
    public int checkLogin(string loginName,string loginPwd) {
        SqlConnection myConn = GetConnection();
        SqlCommand myCmd = new SqlCommand( "select count(*) from tb_User where Name=@loginName and PassWord=@loginPwd",myConn);
        myCmd.Parameters.Add(new SqlParameter("@loginName",SqlDbType.VarChar,20));
        myCmd.Parameters["@loginName"].Value = loginName;
        myCmd.Parameters.Add(new SqlParameter("@loginPwd", SqlDbType.VarChar, 50));
        myCmd.Parameters["@loginPwd"].Value = loginPwd;
        myConn.Open();
        int i = (int)myCmd.ExecuteScalar();
        myCmd.Dispose();
        myConn.Close();
        return i;
              
    }
    /// <summary>
    //// Implementing random captcha
    /// </summary>
    /// <param name="n">number of captchas</param>
    //// <returns> return the generated random number</returns>
    public string RandomNum(int n) {
        string strchar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s, t,u,v,w,x,y,z";
        string[] VcArray = strchar.Split(',');
        string VNum = "";
        int temp = -1;
        Random rand = new Random();
        for (int i=1; i < n + 1; i++) {
            if (temp ! = -1) {
                rand = new Random(i*temp*unchecked((int)DateTime.Now.Ticks));
            }
            int t = rand.Next(61);
            if (temp ! = -1 && temp == t) {
                return RandomNum(n);
            
            }
            temp = t;
            VNum += VcArray[t];
        }
        return VNum;
    
    
    }
}




.aspxのコードは以下の通りです。

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Login" %>
<!DOCTYPE html PUBLIC "-/W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.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>
    <style type="text/css">
    .tbl_login{ padding:10px; margin:10px;}。
    .tbl_login td{ padding:10px; border:1px solid gray;}.
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Table ID="Table1" runat="server" CssClass="tbl_login" >.Abstract:テーブルID="Table1"runat="server"。
            <asp:TableRow runat="server">
            <asp:TableCell>adminName:</asp:TableCell>
            <asp:TableCell><asp:TextBox ID="txt_name" runat="server"></asp:TextBox></asp:TableCell>.XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX;
            </asp:TableRow>
            <asp:TableRow runat="server">
             <asp:TableCell> 管理者パスワード:</asp:TableCell>
            <asp:TableCell><asp:TextBox ID="txt_pwd" runat="server" TextMode="Password"></asp: TextBox></asp:TableCell>
            </asp:TableRow>
            <asp:TableRow ID="TableRow1" runat="server">
             <asp:TableCell>Captcha:</asp:TableCell>
            <asp:TableCell><asp:TextBox ID="txt_code" runat="server" ></asp:TextBox></asp:TableCell>.XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX;
            <asp:TableCell style="border:1px solid silver;">
                <asp:Label ID="lab_Code" runat="server" Text="8888"></asp:Label></asp:TableCell>
            </asp:TableRow>
        </asp:Table>
         <asp:Button ID="btn_login" runat="server" Text="Login" 
            οnclick="btn_login_Click1" />
                 <asp:Button ID="btn_cancel" runat="server" Text="cancel".Button ID="btn_cancel" runat="server"Text="cancel" 
            οnclick="btn_cancel_Click1" />
    </div>
    </form>
</body>
</html>

.aspx.csのコードは以下の通りです。

using System;
Generic;
Linq;
Web;
UI;
WebControls;

public partial class Login : System.Web.UI.
UI.
    CommonClass cc = new CommonClass();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack) {
            this.lab_Code.Text = cc.RandomNum(4);
        
        }
    }
    

    protected void btn_login_Click1(object sender, EventArgs e)
    {
        if (txt_name.Text.Trim() == "" || txt_pwd.Text.Trim() == "")
        {
            Response.Write(cc.MessageBox("Login name and password cannot be empty! ", "Login.aspx"));
        }
        else
        {
            if (txt_code.Text.Trim() == lab_Code.Text.Trim())
            {
                int IntUserIn = cc.checkLogin(txt_name.Text.Trim(), txt_pwd.Text.Trim());
                if (IntUserIn > 0)
                {
                    Response.Write("<script language=javascript> window.open('AdminIndex.aspx');window.close();</script>");
                }
                else
                {
                    Response.Write(cc.MessageBox("Login name or password error! ", "Login.aspx"));

                }

            }
            else
            {
                Response.Write(cc.MessageBox("Captcha error! ", "Login.aspx"));
            }

        }
    }
    protected void btn_cancel_Click1(object sender, EventArgs e)
    {
        Response.Write("<script>window.close();location='javascript:history.go(-1)';</script>");
    }
}


テストは次のように動作します。