In ASP.NET 2.0, the newly added membership provider function, combined with a series of powerful registration and login controls, can easily manage user login and permissions (see << Introduction to ASP.NET 2.0 login controls >>).
However, you may find that the login controls and membership management functions that come with ASP.NET 2.0 are used with SQL Server 2005 Express by default. So, how to change it to use SQL Server 2000 or other data sources? , such as access, oracle, etc.? If you want to rewrite an application to manage logged in users or user permissions in your application, how should you modify it? In this article, we will show how to use a custom provider in ASP.NET 2.0 to cooperate with the login control to implement a simple login process.
In order to understand how the provider in ASP.NET 2.0 works, first look at the following structure diagram:
Field Name Data Type Field Size Username (key) Text 8 Password Text 8 Email Text 50 passwordQuestion Text 50 passwordAnswer Text 50 |
Public Class ModifiedSqlMembershipProvider Inherits SqlMembershipProvider Public Overrides Function CreateUser (...) ... End Function ... End Class |
If you don't want to use the SqlMembershipProvider provided in Visual Studio 2005 beta 2, you only need to declare your own class and inherit the MembershipProvider class. The MembershipProvider class contains membership-related methods and properties.
In Solution Explorer, use "Add New item.." to add a class, name it AccessMembershipProvider.vb, and follow the system prompts to place it in the App_Code directory.
Next, reference the relevant namespace and write the framework of the program as follows:
Imports Microsoft.VisualBasic
Imports System.Data
Public Class AccessMembershipProvider
Inherits MembershipProvider
In order to use a custom provider,
End Class
must make relevant configurations in web.config.You can add a new web.config file and write the following code:
<system.web>
<authentication mode="Forms"/>
<membership
defaultProvider="AccessMembershipProvider" >
<providers>
<add name="AccessMembershipProvider"
type="AccessMembershipProvider"
requiresQuestionAndAnswer="true"
connectionString="Provider=Microsoft.Jet.
OLEDB.4.0;Data Source=C:NewMembershipProvider
App_DataMembers.mdb;Persist Security
Info=False" />
</providers>
</membership>
</system.web>
Among them, please pay attention to the following points:
the authentication method must be selected as "Forms" (authentication mode="forms").
By using the <add> tag, add a custom provider named AccessMembershipProvider.
The requiresQuestionAndAnswer attribute, when its value is true, indicates that during new registration, prompt questions and answers to be answered must be filled in.
ConnectionString, indicates the connection string to connect to the database.
The DefaultProvider attribute indicates which provider the system uses by default, because multiple providers can be set in a system.
In AccessMembershipProvider.vb, add the following private member
Private connStr As String
Private comm As New OleDb.OleDbCommand
Private _requiresQuestionAndAnswer As Boolean
Private _minRequiredPasswordLength As Integer
and add the Initialize() method, the code is as follows
Public Overrides Sub Initialize(ByVal name As String, ByVal config As System.Collections.Specialized.NameValueCollection)
'===retrives the attribute values set in
'web.config and assign to local variables===
If config("requiresQuestionAndAnswer") = "true" Then _
_requiresQuestionAndAnswer = True
connStr = config("connectionString")
MyBase.Initialize(name, config)
End SubWhen
the provider is loaded, the Initialize() method will be called. In the web.config file just now, the various attribute values set using the <add> tag can be read in this method. For example, it can be read by using the config parameter. In the above code, config("connectionString") is used to read the database connection string and put it in the variable connStr variable. After that, set the RequiresQuestionAndAnswer property as follows:
Public Overrides ReadOnly Property _
RequiresQuestionAndAnswer() _
As Boolean
Get
If _requiresQuestionAndAnswer = True Then
Return True
Else
Return False
End If
End Get
End Property
Note that the value of this property must be set, otherwise, in the CreateUserWizard control, the two text boxes of password prompt question and password prompt answer will not be displayed.
Next, we can start writing the code to create a new user. The code of the CreateUser() method is as follows:
Public Overrides Function CreateUser(ByVal username As String, ByVal password As String, ByVal email As String, ByVal passwordQuestion As String, ByVal passwordAnswer As String , ByVal isApproved As Boolean, ByVal providerUserKey As Object, ByRef status As System.Web.Security.MembershipCreateStatus) As System.Web.Security.MembershipUser
Dim conn As New OleDb.OleDbConnection(connStr)
Try
conn.Open()
Dim sql As String = "INSERT INTO Membership VALUES (" & _
"@username, @password, @email, " & _
" @passwordQuestion, @passwordAnswer )"
Dim comm As New OleDb.OleDbCommand(sql, conn)
comm.Parameters.AddWithValue("@username", username)
comm.Parameters.AddWithValue("@password", password)
comm.Parameters.AddWithValue("@email", email)
comm.Parameters.AddWithValue("@passwordQuestion", passwordQuestion)
comm.Parameters.AddWithValue("@passwordAnswer", passwordAnswer)
Dim result As Integer = comm.ExecuteNonQuery()
conn.Close()
status = MembershipCreateStatus.Success
Dim user As New MembershipUser("AccessMembershipProvider", username, Nothing, email, passwordQuestion, Nothing, True, False, Now, Nothing, Nothing, Nothing, Nothing)
Return user
Catch ex As Exception
status = MembershipCreateStatus.UserRejected
Return Nothing
End Try
End Function
Let’s interpret the above code. First, we insert a record into the database. After the new user is successfully added, we must return a status information status (the status is passed in as ByRef status As System.Web.Security .MembershipCreateStatus method), and we want to return an instance of the MembershipUser class, so we return its instance in this way:
Dim user As New MembershipUser("AccessMembershipProvider", username, Nothing, email, passwordQuestion, Nothing, True , False, Now, Nothing, Nothing, Nothing, Nothing)
Among them, there are many constructors that use the methods of the MembershipUser class. For details, you can check MSDN. Here we only use username, email, passwordQuestion, createddate (account creation date , NOW is used here).
On the login page, in order to determine whether a legitimate user is logging in, you need to write the following code:
Public Overrides Function ValidateUser( _
ByVal username As String, _
ByVal password As String) As Boolean
Dim conn As New OleDb.OleDbConnection(connStr)
Try
conn.Open()
Dim sql As String = _
"Select * From Membership WHERE " & _
" username=@username AND password=@password "
Dim comm As New OleDb.OleDbCommand(sql, conn)
comm.Parameters.AddWithValue("@username", _
username)
comm.Parameters.AddWithValue("@password", _
password)
Dim reader As OleDb.OleDbDataReader = _
comm.ExecuteReader
If reader.HasRows Then
Return True
Else
Return False
End If
conn.Close()
Catch ex As Exception
Console.Write(ex.ToString)
Return False
End Try
End Function
is just like this, a simple custom provider is completed, which can be used with login, registration and other controls. When you run the program, the user registration page first appears. When the user successfully registers, the user will be directed to the login page, as shown in the following figure: