Sample Code for Creating Custom Membership Provide

2020-02-26 12:00发布

问题:

I am writing an MVC 3 application and I am trying to implement my own custom membership provider (following the sample in Apress' Pro ASP.NET MVC 3 Framework).

I created my custom class, inherited from MembershipProvider and (using ReSharper) implemented all 27 of the methods with NotImplementedExceptions.

Now, I have overridden the ValidateUser method as the book states and it works fine, but I would like to make my provider more robust and implement the other methods (e.g. set MinRequiredPasswordLength and GetNumberOfUsersOnline).

Is there some sample code that I can use to start populating these methods that I can tweak to fit my own DB/Model schema?

I can certainly use trial and error to figure it out, but a base code sample would greatly help.

EDIT: This question was just downvoted twice. If you are going to downvote, please post a comment as to why so that I can work on improving my questions.

EDIT 2: For example, for the following method:

public override int GetNumberOfUsersOnline()
{
  throw new System.NotImplementedException();
}

I can try to write code from scratch to look at some web log, determine the users login time and approximate if they are still on, but that will take a large amount of time for me to figure out. Since all this code is from the same interface that Microsoft wrote for the standard SqlMembershipProvider, isn't there code out there (even from MS) that contains this method? If so, I want take it, modify it so it uses my DB schema instead of the aspnetdb default schema. I would prefer to have some sort of base code to work from. I thought this would be a simple and fairly standard request, but perhaps not.

回答1:

You can't use the default provider's code for your custom provider, that is why you are implementing a custom one, to tweak it according to your requirements, use your own db tables etc.

Take a look at my blog posts about custom membership, custom role providers and custom membership user. There is an example there of how you can use your own database to get/set membership information.



回答2:

Here's a of sample implementation of custom MembershipProvider on MSDN.

http://msdn.microsoft.com/en-us/library/6tc47t75.aspx