The problem of membership class and database in MVC

Source: Internet
Author: User

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.

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.