On tech ed 2005, I introduced Asp.net 2.0. In this article, Asp.net 2.0 provides many functions, allowing Program There were a lot of people doing less, which caused everyone to wonder: what is the custom capability of Asp.net 2.0? What is scalability? Can programmers expand what Microsoft provides? Below, I have examined the provider of Asp.net 2.0, combined with the information compiled below, explains how to customize the provider in the use of the login control, at the same time can refer to the role (this article is also published in the http://dev.yesky.com/msdn/373/2128373.shtml? On 412)
InIn Asp.net 2.0, the newly added membership provider feature and a series of powerful registration and login controls allow you to conveniently manage user login and permissions (see
<Asp.net 2.0 login controls> Article (http://www.yesky.com/466/1870966.shtml ).
However, you may find that,These login controls and membership management functions provided by Asp.net 2.0 are used with SQL Server 2005 express by default. How can we change them to SQL Server 2000 or other data sources, what about access and Oracle? If you want to re-write an application for login user or user permission management in the application, how can you modify it? In this article, we will show how to use a custom provider in Asp.net 2.0 to implement a simple login process with the login control.
To understandHow does the provider in Asp.net 2.0 work? First, let's look at the following structure:
It can be clearly seen that the top layer is various login controls, and the bottom layer is the membership API related to member. In the membership API, the membership class performs operations on users, such as adding or deleting users, while the membershipuser class stores personal information about users, such as user names, passwords, and emails.
In Visual Studio 2005 beta 2, SQL express membership provider is used by default. The role of provider is to communicate with membership APIs and databases, so that users do not need to care about the database to be used. All operations can be implemented using various corresponding data providers.
But most of the time, Asp. by default, the provider supported by NET 2.0 cannot meet its needs. We can compile the provider as needed. this article describes how to use an Access database to create a data table and store user information. The methods described in this article can also be applied to other databases.
First, open Visual Studio 2005 beta 2 and select VB. NET to create a web site. In this example, we set a user registration form and a login form for the sake of simplicity. New users can register the form before logging in.
Next, drag and drop a createuserwizard control to the default form. This is an automatic control provided by the system to create a user, and you can easily create a user. To make the page look beautiful, click "smart sensing" in the upper-right corner of the control and select "auto format". In the displayed form, select the "elegant" style, as shown in:
Of course, we can modify the text prompt of this control at will. To enable users to go To the login page after registration, set the value of the continuedestinationpageurl attribute of the control to login. aspx, and write the page.
Then, drag a loginview control to the default. aspx page. In this control, you can set two templates: anonymous template, which indicates the status that the visitor sees before the user logs in. The loggedin template indicates that after the user successfully logs in, the status you see (here you can set some text display, such as welcome to enter, and the user name is usually displayed ).
Here, in the loggedin template of the loginview control, we enter "you are logged in" and add a loginname and a loginstatus control. The loginname control displays the user ID after login, while the loginstatus control displays the Logout link after the user logs on. See the following two figures:
Add a new form named login. aspx to the project, and add a login control to the form, as shown in figure
Next, we need to create a database. In the working directory, use access to create a database named members. mdb, as shown in the data structure table:
Field Name Data Type field size
Username (key) text 8
Password text 8
Email text 50
Passwordquestion text 50
Passwordanswer text 50
Before creating your own provider, we should first understand the provider construction in ASP. NET 2.0. In ASP. NET 2.0 Beta 2, the default sqlmembershipprovider inherits the membershipprovider class, And the membershipprovider class inherits from the providerbase class, as shown in
To modify an existing SQL membership provider, you only need to create a class that inherits the sqlmembershipprovider class and overwrites its method. For example:
Public class modifiedsqlmembershipprovider Inherits sqlmembershipproviderPublic overrides function createuser (...) ... End Function ... End Class |
If you do not want to use 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 methods and attributes related to membership.
In Solution Explorer, use "Add new item..." to add a class named accessmembershipprovider. VB, and put it in the app_code directory as prompted.
Next, reference the relevant namespace and write the program framework as follows:
Imports Microsoft. VisualBasic Imports system. DataPublic class accessmembershipprovider Inherits membershipprovider End Class |
To use a custom provider, you must configure it in Web. config. You can add a new Web. config file and write the followingCode:
<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_data \ members. mdb; persist Security Info = false "/> </Providers> </Membership> </System. Web> |
Pay attention to the following points:
The authentication method must be "forms" (Authentication mode = "forms ").
Add a custom provider named accessmembershipprovider by using the <add> label.
When the requiresquestionandanswer attribute is set to true, it indicates that the question and answer to be answered must be entered during new registration.
Connectionstring, indicating the connection string for database connection.
Defaultprovider attribute, indicating which provider is used by the system by default, because multiple providers can be set in one system.
In accessmembershipprovider. VB, add the following private members:
Private connstr as string Private comm as new oledb. oledbcommand Private _ requiresquestionandanswer as Boolean Private _ minrequiredpasswordlength as integer |
And the initialize () method is added. 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 sub |
When the provider is loaded, the initialize () method is called. In the Web. config file, all attribute values set using the <add> label can be read in this method. For example, you can use the config parameter to read data. In the above code, you can use config ("connectionstring") to read the database connection string and put it in the variable connstr. Then, set the requiresquestionandanswer attribute 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 attribute must be set. Otherwise, the password prompt and password prompt answer text boxes are not displayed in the createuserwizard control.
Next, we can start to compile the code for creating a user. The code for 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) Return user Catch ex as exception Status = membershipcreatestatus. userrejected Return nothing End try End Function |
Let's explain the above Code. First, we inserted a record into the database. After the new user is successfully added, we must return a status information status (this status is passed in with byref status as system. web. security. in membershipcreatestatus mode), 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) |
There are many constructors using the membershipuser class methods. For details, refer to msdn. Here we only use username, email, passwordquestion, and createdate (Account creation date, now ).
On the login page, you need to write the following code to determine whether a logon is valid:
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 |
in this way, a simple custom provider is complete. You can use it with logon, registration, and other controls. To run the program, the user registration page appears. After the user is successfully registered, the user is directed to the login page, as shown in:
after the user successfully logs in, as shown in: