To create an ASP. NET application Form validation using C#.net

Source: Internet
Author: User

Open Visual Studio. NET.
Create a new ASP. NET WEB application and specify the name and location of the application.
Configuring security settings in the Web. config file

This section demonstrates how to add and modify the < authentication > and < authorization > configuration section to configure an ASP. NET application to use forms-based authentication.
In Project Explorer, open the Web. config file.
Change the authentication mode to forms (form).
3. Insert the tag and fill in the appropriate properties. (For more information about these properties, see the MSDN documentation or the QuickStart documentation that is listed in the References section.) Copy the following code, and then click Paste as HTML on the Edit menu to paste the code in the file section:

protection= "All" path= "/" timeout= "/>

Deny access to anonymous users in the section (shown below):



Create a sample database table to store user details

This section demonstrates how to create a sample database table to store users ' user names, passwords, and roles. If you want to store user roles in a database and implement role-based security, you need a role column.
On the Start menu, click Run, and then type Notepad to open Notepad.
Highlight the following SQL script code, right-click the code, and then click Copy. In Notepad, click Paste on the Edit menu to paste the following code:
if exists (select * from sysobjects where id =
OBJECT_ID (N ' [dbo].[ Users] ') and OBJECTPROPERTY (ID, N ' isusertable ') = 1)
drop table [dbo]. [Users]
GO
CREATE TABLE [dbo]. [Users] (
[uname] varchar not NULL,
[PWD] varchar not NULL,
[userrole] varchar not NULL,
) on [PRIMARY]
GO
ALTER TABLE [dbo]. [Users] With NOCHECK ADD
CONSTRAINT [pk_users] PRIMARY KEY nonclustered
(
[Uname]
) on [PRIMARY]
GO

INSERT into Users values (' User1 ', ' user1 ', ' Manager ')
INSERT into Users values (' user2 ', ' user2 ', ' Admin ')
INSERT into Users values (' User3 ', ' user3 ', ' User ')
GO

Save the file as Users.sql.
On the Microsoft SQL Server computer, open users.sql in Query Analyzer. In the list of databases, click Pubs, and then run the script. This will create a sample user table and use this sample application to populate the table in the Pubs database that you want to use.
Create Logon.aspx Page

Add a new Web form to the project named Logon.aspx.
Open the Logon.aspx page in the editor and switch to HTML view.
Copy the following code, and then use the Paste as HTML option on the Edit menu to insert the code into the

Between tags:

Logon Page
Email:
Password:
Persistent cookies:


This Web form is used to provide the user with a login form so they can provide the user name and password to log in to the application.
Switch to Design view and save the page.
Encode the event handler to validate the user credentials

This section describes the code that is located in the code-behind page (Logon.aspx.cs).
Double-click Logon to open the Logon.aspx.cs file.
Import the required namespaces in the code-behind file:
Using System.Data.SqlClient;
Using System.Web.Security;

Create the ValidateUser function to validate the user credentials by locating the database. (Be sure to change the connection string to point to the database.) )
private bool ValidateUser (string userName, String PassWord)
{

SqlConnection Conn;  SqlCommand cmd;string lookuppassword = null;//Check for invalid username.//userName must not being null and must be between 1 and Characters.if ((null = = UserName) | | (0 = = username.length) | | (Username.length > 15))    {System.Diagnostics.Trace.WriteLine ("[ValidateUser] Input validation of UserName failed."); return false;} Check for invalid password.//passWord must not being null and must be between 1 and characters.if ((null = = Passwor D) | | (0 = = password.length) | | (Password.length > 25))    {System.Diagnostics.Trace.WriteLine ("[ValidateUser] Input validation of PassWord failed."); return false;}  try{//Consult with your SQL Server administrator for a appropriate connection//string to use to connect to your    Local SQL Server.    conn = new SqlConnection ("server=localhost;integrated security=sspi;database=pubs"); Conn.    Open ();   Create SqlCommand to select PWD field from users table given supplied UserName. cmd = new SqlCommand ("Select pwd from Users where [email protected]", conn); Cmd.    Parameters.Add ("@userName", SqlDbType.VarChar, 25); Cmd. parameters["@userName"].    Value = UserName;    Execute command and Fetch pwd field into Lookuppassword string. Lookuppassword = (string) cmd.    ExecuteScalar ();    Cleanup command and Connection objects. Cmd.    Dispose (); Conn. Dispose ();}    catch (Exception ex) {//ADD error handling here for debugging.    This error message should not being sent back to the caller. System.Diagnostics.Trace.WriteLine ("[ValidateUser] Exception" + ex. Message);} If no password found, return false.if (null = = Lookuppassword) {//You could write failed login attempts    Event log for additional security. return false;} Compare lookuppassword and input PassWord, using a case-sensitive comparison.return (0 = = string. Compare (Lookuppassword, PassWord, false));

}

You can use one of two methods to generate a form authentication Cookie and redirect the user to the appropriate page in the cmdLogin_ServerClick event. Sample code is provided for two scenarios. One of these can be used as needed.
Call the RedirectFromLoginPage method to automatically generate the forms authentication Cookie and redirect the user to the appropriate page in the cmdLogin_ServerClick event:
private void cmdLogin_ServerClick (object sender, System.EventArgs e)
{
if (ValidateUser (Txtusername.value,txtuserpass.value))

FormsAuthentication.RedirectFromLoginPage(txtUserName.Value,    chkPersistCookie.Checked);else    Response.Redirect("logon.aspx", true);

}

Generates an authentication ticket, encrypts it, creates a Cookie, adds it to the response, and redirects the user. This allows you to better control how cookies are created. In this example, you can also include custom data and FormsAuthenticationTicket.
private void cmdLogin_ServerClick (object sender, System.EventArgs e)
{
if (ValidateUser (Txtusername.value,txtuserpass.value))
{
FormsAuthenticationTicket tkt;
String cookiestr;
HttpCookie ck;
tkt = new FormsAuthenticationTicket (1, txtUserName.Value, DateTime.Now,
DateTime.Now.AddMinutes (+), chkpersistcookie.checked, "Your custom Data");
cookiestr = Formsauthentication.encrypt (tkt);
ck = new HttpCookie (Formsauthentication.formscookiename, cookiestr);
if (chkpersistcookie.checked)
Ck. Expires=tkt. expiration;

        

RESPONSE.COOKIES.ADD (CK);

String strredirect;
strredirect = request["ReturnUrl"];
if (strredirect==null)
strredirect = "default.aspx";
Response.Redirect (strredirect, true);
}
Else
Response.Redirect ("Logon.aspx", true);
}

Ensure that the following code is added to the InitializeComponent method of the code generated by the Web Forms Designer.
This.cmdLogin.ServerClick + = new System.EventHandler (This.cmdlogin_serverclick);

Create a Default.aspx page

This section creates a test page where the user is redirected after authentication. If users browse this page without first logging in to the application, they are redirected to the sign-in page.
Rename the existing WebForm1.aspx page to Default.aspx and open it in the editor.
Switch to HTML view and copy the following code between the tags:

This button is used to unregister the forms authentication session.
Switch to Design view and save the page.
Import the required namespaces in the code-behind file:
Using System.Web.Security;

Double-click SignOut to open the code-behind page (Default.aspx.cs) and copy the following code in the cmdSignOut_ServerClick event handler:
private void cmdSignOut_ServerClick (object sender, System.EventArgs e)
{
FormsAuthentication.SignOut ();
Response.Redirect ("Logon.aspx", true);
}

Make sure that the following code has been added to the InitializeComponent method of the Web forms Designer generated code:
This.cmdSignOut.ServerClick + = new System.EventHandler (This.cmdsignout_serverclick);

Save and compile the project. You are now ready to execute the application.

To create an ASP. NET application Form validation using C#.net

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.