Search code examples
asp.netmembership

Membership.CreateUser should fail but doesn't


I'm creating users for test purposes, using :

string username = ...
string password = ...
string email = "******** not a valid email address! *********";
MembershipUser NewUser = Membership.CreateUser(userName, password, email, "no question", "no answer", true, out createStatus);
if (NewUser == null)
{
  switch (createStatus)
  {
    case MembershipCreateStatus.DuplicateUserName:
      throw new Exception("There already exists a user with this username.");
    case MembershipCreateStatus.InvalidEmail:
      throw new Exception("There email address you provided in invalid.");
    case MembershipCreateStatus.InvalidPassword:
      throw new Exception("The password you provided is invalid. It must be seven characters long.");
    default:
      throw new Exception("There was an unknown error; the user account was NOT created.");
  }
}

When this gets executed, a new user will get created, it doesn't fail with NewUser==null, MembershipCreateStatus.InvalidEmail, which is what I would expect.

Any idea why?

Here's the membership section from config if that has a bearing, although I don't see how:

    <membership defaultProvider="myProvider">
  <providers>
    <add
            name="myProvider"
            applicationName="/"
            connectionStringName="myconnectionsString"
            enablePasswordRetrieval="true"
            enablePasswordReset="true"
            passwordFormat="Clear"
            requiresQuestionAndAnswer="false"
            requiresUniqueEmail="true"
            minRequiredNonalphanumericCharacters="0"
            type="System.Web.Security.SqlMembershipProvider"
            />
  </providers>
</membership>

Thanks in advance!


Solution

  • From reflector this is the validation on email in SqlMembershipProvider

      if (!SecUtility.ValidateParameter(ref email, this.RequiresUniqueEmail, this.RequiresUniqueEmail, false, 0x100))
        {
            status = MembershipCreateStatus.InvalidEmail;
            return null;
        }
    
    internal static bool ValidateParameter(ref string param, bool checkForNull, bool checkIfEmpty, bool checkForCommas, int maxSize)
    {
        if (param == null)
        {
            return !checkForNull;
        }
        param = param.Trim();
        return (((!checkIfEmpty || (param.Length >= 1)) && ((maxSize <= 0) || (param.Length <= maxSize))) && (!checkForCommas || !param.Contains(",")));
    }
    

    Looks like it doesn't care abut valid email or not, just that something is provided. You'll want to handle it from your client or override the SqlMembershipProvider.