I have received many comments and questions about how you can do what is described in this post when you site requires question and answer. (Better solution at the bottom of this post)
The solution is definitely not the best and should be used with EXTREME caution because in a high traffic website can cause problems but I write it down anyway.
We will use reflection in order to solve our problem.
And this is the code
MembershipUser user = Membership.GetUser();
string newPassword = "newPass";
string tempPassword = string.Empty;
if (Membership.Provider.RequiresQuestionAndAnswer)
{
var _requiresQA = Membership.Provider.GetType().GetField("_RequiresQuestionAndAnswer",
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
//change the value in the private field
_requiresQA.SetValue(Membership.Provider, false);
//do the reset
tempPassword = user.ResetPassword();
//set it's original value
_requiresQA.SetValue(Membership.Provider, true);
}
else
{
tempPassword = user.ResetPassword();
}
//do the Change
user.ChangePassword(tempPassword, newPassword);
But this code changes the only instance of MembershipProvider meaning if you access somewhere else from your application the property RequiresQuestionAndAnswer until you set back it’s original value you will get false instead of true.
So again be VERY careful.
OR
You can ignore the above and use the brilliant and simple solution that RichardD suggested in comments.
Add this to your web.config

The concept is to use one provider for password reset and one provider for every other function in your site.
And the code becomes like this

Beautiful isn’t it?
Hope you find it useful!
Note: The above solution is only when you store your passwords in a Hashed way. In any other occasion the above solution is pointless.
Republished from djsolid - scratching discs of code & entrepreneurship [19 clicks].
Read the original version here [1 clicks].