The problem of membership class and database in MVC

Source: Internet
Author: User
Tags microsoft sql server

Membership they use the ASPNETDB database, but we can use our custom database, but unless our custom database has the same pattern as this aspnetdb, Otherwise, the default SqlMembershipProvider provided by ASP will not be used.
That is, if we were to use the SqlMembershipProvider provided by ASP, we would have to aspnetdb the database file or its copy. Obviously, this is not what we want.
To do this, if we use a custom database (rather than a copy of Aspnetdb), then we have to write our own membershipprovider. The steps are as follows.
1, define your own database, in this case TestDB01. Under my TestDB01 there is a table userinfo, under which there is a field userid,username,userage.
2, write your own membershipprovider, this class inherits from the MembershipProvider class under the namespace System.Web.Security. This step is very simple, create an empty class, for example named Mymembershipprovider, technically we can put it anywhere in the application, but I put it under the project under a folder named infrastructure (self-added).
The initial code form for this step is probably as follows:
Namespace Mvcapplication5.infrastructure
{
Public class mymembershipprovider:system.web.security.membershipprovider/* I wrote the namespace here. */
{
}

Of course, it's empty, it needs us to add something to it.
At this point we put the cursor on "System.Web.Security.MembershipProvider" and right click on the mouse, in the popup drop-down box we can see "Implement Virtual Class" (I use the English version, I do not know if there is no translation, the original content is " Emplement Abstract class "), click this option our Mymembershipprovider this class immediately more than n more methods, at this time its form is as follows (I only cut a part):
public class MyMembershipProvider:System.Web.Security.MembershipProvider
{
public override string ApplicationName
{
Get
{
throw new NotImplementedException ();
}
Set
{
throw new NotImplementedException ();
}
}

public override bool ChangePassword (string username, string OldPassword, String newpassword)
{
throw new NotImplementedException ();
}

//...

public override bool ValidateUser (string Username, string password)
{
throw new NotImplementedException ();
}
}
As you can see, these methods do nothing except throw a NotImplementedException exception. Of course, this is not what we want, these methods need our own to fill, otherwise how to call "Custom" it.
Well, let's just take a look at the last ValidateUser () method first, regardless of the other method. As the name implies, this is the method we use to verify the user, and modify it as follows:
public override bool ValidateUser (string Username, string password)
{
SqlConnection sqlconn = new SqlConnection ("Data source=hcng-pc;initial catalog=testdb01;integrated security=true");/* Replace HCNG-PC with your data source name, and TestDB01 is the custom database I used to test */
SqlCommand sqlcmd = new SqlCommand ("Select UserID, UserName from [UserInfo] where UserName = @userName and userage = @user Age ", sqlconn); * * These believe you understand that if there is no doubt, please add the question * *

Try
{
Sqlconn. Open ();

sqlcmd. Parameters.Add (New SqlParameter ("@userName", SqlDbType.NVarChar, 50));
sqlcmd. parameters["@userName"]. Value = Username. Trim ();
sqlcmd. Parameters.Add (New SqlParameter ("@userAge", Sqldbtype.smallint, 2));
sqlcmd. parameters["@userAge"]. Value = password;

SqlDataReader sqlrd = sqlcmd. ExecuteReader ();
if (sqlrd.hasrows)
{
return true;
}

return false;
}
catch (Exception ex)
{
throw new Exception (ex. Message);
}
}
At this point, our custom MembershipProvider is complete.
3, configure Web. config. Replace the default <membership> node under the <system.web> node under this configuration file with the following:
<system.web>
<membership defaultprovider= "Mymembershipprovider" >
<providers>
<clear/>
<add name= "Mymembershipprovider" <!--first three lines to use the name: -->type= "MvcApplication5.Infrastructure.MyMembershipProvider"/><!--be careful not to miss the name of the namespace. -
</providers>
</membership>
4, the work is basically completed, only to see the effect.
Add a Default1controller under the project, and under this Default1controller, add the following action:
[HttpPost]
Public ActionResult Index (string Username, string password)
{
if (Membership.ValidateUser (username, password))
{
viewdata["message"] = "OK";
}
Else
{
viewdata["message"] = "NO";
}

return View ();
}
Found it, with a membership.validateuser () on the line.

I believe at the same time you also found that such a custom membershipprovider seems to have not played any special role, at least I think so.
And it's best not to have login controls in MVC, so if we're customizing MembershipProvider in MVC It's no different than writing our own membership management logic.

If you really want to use a custom MembershipProvider, then the above code is obviously not enough, such as System.Web.Security.MembershipProvider's first Method ChangePassword (), It is used to change the user's password, which requires the code we write ourselves to implement its logic.
Then the second method, Changepasswordquestionandanswer (), is used to provide the user with the answer to the change question, and the third method CreateUser () is used to create a new user:

The above is MembershipProvider, and then there is RoleProvider, which is part of a custom RoleProvider:
public class Myroleprovider:roleprovider
{
public override string[] GetRolesForUser (string username)
{
if (username = = "Steve")
return new string[] {"Approvedmember", "Commentsmoderator"};
Else
return new string[] {};
}
/* Omitted part */
}
Of course, about RoleProvider, to say also has its web. config node configuration, I hope you check the Internet, if you are still sure you want to use it.

There is a custom profileprovider, the same as before, and if you are sure you want to use it.

---------------------------------membership automatically generate database and database access----------------------------------------------------------------- -----
By executing the "aspnet_regsql" command, you can automatically create 11 tables in a database and provide several API methods to manipulate the 11 tables.
However, the design of these 11 tables is often not in line with the requirements, if the expansion, it will be more troublesome. There are two common ways to extend:do not change the original table, but to build a table corresponding to the previous table, the ID of the table is identical to the original table;Change the design of the original table
Run the Netframwork tool ASP. NET SQL Server Registration tool (aspnet_regsql.exe)
Path: [Drive:]\windows\microsoft.net\framework\versionnumber folder

The ASP. NET SQL Server Registration tool is used to create a Microsoft SQL Server database for use by SQL Server providers in ASP. NET, or to add or remove options from an existing database.
You can run Aspnet_regsql.exe without any command-line arguments to run a wizard that guides you through the process of specifying connection information for a SQL Server installation and for membership, Role Manager, profile, Web Features such as component Personalization and health monitoring install or remove database elements. (The wizard does not involve setting session state and SQL cache dependencies.) Using the options listed in the following table, you can also run aspnet_regsql.exe as a command-line tool to specify the database elements to add or remove for each feature.


Aspnet_regsql.exe parameter explanation
-General information and functions
-W is the way of the wizard, which is the graphical interface.
-C Connection string,-if SQL Server is already installed, you can use this parameter to connect to the database
-s server name, which can be the name of the database or the name of the instance
-u username, the user name of the login database, which is typically used to create database tables or database scripts.
-p password,-the password to log in to the database. Generally-u and-P always appear together
-E, without any parameters, which identifies you will use the current Windows user as the user connecting to the database.
-d database name, use this parameter to establish the corresponding database name, if not specified will default to the ' Aspnetdb ' database
-sqlexportonly filename, parameter is the name of the file to be saved, and the parameter identifies only the script and configuration script for the database, without any action.
-A all|m|r|p|c|w,-a means to allow or open a function, M for membership function, R for Role management function, p for the profile function, C for Web Parts personalization, W for Web events, all for open/ All of the above features are available
-R all|m|r|p|c|w-r for removing or prohibiting a feature, m for membership function, R for role management, p for profile, C for Web Parts personalization, W for Web events, all for forbidden/ Turn off all of the above features
For example: Aspnet_regsql.exe–a p–e
--session State Feature
-ssadd, open/Available SQL Server mode session state mode
-ssremove, close/Remove SQL Server mode session state mode
-sstype t|p|c, specify a specific way, t means that the data and State of session states will be placed in the SQL Server ' tempdb ' database, the management scripts and stored procedures will remain in the "ASPState" database, if the machine starts, The session state will not be saved, which is also the default setting. P indicates that the data and status of the session state and the associated stored procedures will be placed in the SQL Server ' ASPState ' database; C means that the data and State of the session and the associated stored procedures will be placed in the SQL specified by the-d parameter Server's Database
For example: Aspnet_regsql-s localhost-u sa-p wrox-ssadd-sstype P
--sql Cache Dependency Features
-ed, no parameter representation, available/Open SQL Cache Dependency feature
-DD, no parameters, indicates the Disable/disable SQL Cache Dependency feature
-et, no arguments, but must be followed by the-t parameter, which indicates that the table is open/can use the SQL Cache Dependency feature
-DT, no parameters, but must be followed by the-t parameter, which represents the Disable/close SQL Cache Dependency attribute for a table
-T table name, a database table name that must be used with-et or-DT
-LT, without parameters, will query the database, listing all database tables using the QL Cache Dependency feature
For example: Aspnet_regsql.exe-s localhost-u sa-p password-d northwind-t products–et

The problem of membership class and database in MVC

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.