ASP.NET Web Pages - Adding Login
Learn ASP.NET Web Pages by building a web site from scratch.
Part IV: Adding Membership registration, and Login.
What We Will Do
In this chapter we will:
- Create a WebSecurity database
- Initialize WebSecurity in AppStart
- Add a membership registration page
- Add a member login page
The WebSecurity Object
The WebSecurity Object provides security and authentication for
ASP.NET Web Pages applications.
With the WebSecurity object you can create user accounts, login and logout users,
reset or change passwords, and more.
Creating a Web Security Database
A common way to add security to a web site, is to use an authentication
database.
In its simplest form, an authentication database contains a list of
registered users with passwords.
Create a new SQL Server Compact database in the App_Data
folder of your web.
Name the database "Users.sdf".
If you don't know how to create a database for your web, please go to the
chapter Web Database.
 |
You don't have to create a new database.
You can create a new table named Users in your existing database (Northwind.sdf).
|
Create an AppStart Page
In your web folder (DemoWebPages), create a new page named _AppStart.cshtml.
Replace the content of the page with this code:
_AppStart.cshtml
@{
WebSecurity.InitializeDatabaseConnection("Users", "UserProfile",
"UserId", "Email", true);
}
The code above will be run each time your web site (application) starts. It
will initialize a WebSecurity database, with user profiles, logins, passwords, and membership
information (if it is not
already initialized).
"Users" is the name of the database.
"UserProfile" is the name of the database table that
contains the user profile information.
"UserId" is the name of the (integer) column that
contains the user IDs.
"Email" is the name of the (string) column that contains
user names.
true is a boolean value indicating that
the user profile and
membership tables should be created automatically if they don't exist. Otherwise
set to false.
 |
Although true indicates that the membership tables can be created automatically, the
database itself
must always exist.
|
Edit The Style Sheet
Edit your style sheet (Site.css):
Add the following CSS code to the end of the CSS file:
Site.css
/* Forms */
fieldset label
{
display:block;
padding:4px;
}
input[type="text"],input[type="password"]
{
width:300px;
}
input[type="submit"]
{
padding:4px;
}
Add a Registration Page
In your web folder (DemoWebPages), create a new file named "Register.cshtml".
Put the following code inside the file:
Register.cshtml
@{Layout = "Layout.cshtml";
// Initialize page
var email = "";
var password = "";
var confirmPassword = "";
var ErrorMessage = "";
// If this is a POST request, validate and process data
if (IsPost)
{
email = Request.Form["email"];
password = Request.Form["password"];
confirmPassword = Request.Form["confirmPassword"];
if (email.IsEmpty()
|| password.IsEmpty())
{ErrorMessage = "You must specify both
email and password.";}
if (password != confirmPassword)
{ErrorMessage = "Password and confirmation do not match.";}
//
If all information is valid, create a new account
if (ErrorMessage=="")
{
var db = Database.Open("Users");
var user = db.QuerySingle("SELECT Email FROM UserProfile
WHERE LOWER(Email)
= LOWER(@0)", email);
if (user == null)
{
db.Execute("INSERT INTO UserProfile (Email)
VALUES (@0)", email);
WebSecurity.CreateAccount(email,
password, false);
// Navigate back to the
homepage and exit
Response.Redirect("Default.cshtml");
}
else
{ErrorMessage
= "Email address is already in use.";}
}
}
if (ErrorMessage!="")
{
<p>@ErrorMessage</p>
<p>Please correct the errors and try
again.</p>
}
}
<h1>Register</h1>
<form method="post"
action="">
<fieldset>
<legend>Sign-up Form</legend>
<ol>
<li>
<label>Email:</label>
<input type="text" id="email" name="email" />
</li>
<li>
<label>Password:</label>
<input type="password"
id="password" name="password" />
</li>
<li>
<label>Confirm
Password:</label>
<input type="password" id="confirmPassword" name="confirmPassword"
/>
</li>
<li>
<p><input type="submit" value="Register" /></p>
</li>
</ol>
</fieldset>
</form>
Add a Login Page
In your web folder (DemoWebPages), create a new file named "Login.cshtml".
Put the following code inside the file:
Login.cshtml
@{Layout="Layout.cshtml";
// Initialize page
var username = "";
var password = "";
var ErrorMessage = "";
// If this is a POST
request, validate and process data
if (IsPost)
{
username = Request.Form["username"];
password = Request.Form["password"];
if (username.IsEmpty() || password.IsEmpty())
{ErrorMessage
= "You must specify a username and password.";}
else
{
// Login, Navigate back to the homepage and exit
if (WebSecurity.Login(username,
password, false))
{Response.Redirect("Default.cshtml");}
else
{ErrorMessage = "Login failed";}
}
}
if (ErrorMessage!="")
{
<p>@ErrorMessage</p>
<p>Please correct the errors and try
again.</p>
}
}
<h1>Login</h1>
<form method="post"
action="">
<fieldset>
<legend>Log In to Your Account</legend>
<ol>
<li>
<label>Username:</label>
<input type="text" id="username"
name="username" />
</li>
<li>
<label>Password:</label>
<input
type="password" id="password" name="password" />
</li>
<li>
<p><input type="submit" value="login" /></p>
</li>
</ol>
</fieldset>
</form>
Congratulations
You have added membership registration and login information to your website.
Thank You For Helping Us!
Your message has been sent to W3Schools.
Close [X]