title: ASP.NET MVC Identity Email/Username with Special Characters
body: <p>When registering an account through <strong>Web API</strong> with an email such as &quot;xxx-yyy@gmail.com&quot;, Fiddler returns the follow error. <em>Note that email is used for username as well, so both fields are the same</em>. But it works when registering on MVC itself.</p>
  <blockquote>
  <p>ExceptionMessage=User Creation Failed - Identity Exception. Errors were:</p>
  <p>User name xx-yyy@gmail.com is invalid, can only contain letters or digits.</p>
  </blockquote>
  <p><strong>User Object</strong></p>
  <pre><code> var newUser = new ApplicationUser {
              UserName = user.Email,
              Email = user.Email
          };
  </code></pre>
  <p><strong>IdentifyConfig.cs</strong></p>
  <pre><code>public static ApplicationUserManager Create(IdentityFactoryOptions&lt;ApplicationUserManager&gt; options, IOwinContext context) {
          var manager = new ApplicationUserManager(new UserStore&lt;ApplicationUser&gt;(context.Get&lt;ApplicationDbContext&gt;()));
          // Configure validation logic for usernames
          manager.UserValidator = new UserValidator&lt;ApplicationUser&gt;(manager) {
              RequireUniqueEmail = true,
              AllowOnlyAlphanumericUserNames = false
  
          };
  </code></pre>
  <p>I have tried commenting out <em>AllowOnlyAlphanumericUserNames</em> but it didn't work. By right setting it to false should allow special characters, in my case a hyphen(-).</p>
  <p><strong>API Controller</strong></p>
  <pre><code>// POST: api/auth/register
      [ActionName(&quot;Register&quot;)]
      public async Task&lt;HttpResponseMessage&gt; PostRegister(Auth user) {
  
  
          //dash issue is here. 
  
          var userContext = new ApplicationDbContext();
  
          var userStore = new UserStore&lt;ApplicationUser&gt;(userContext);
  
          var userManager = new UserManager&lt;ApplicationUser&gt;(userStore);
  
          var newUser = new ApplicationUser {
              UserName = user.Email,
              Email = user.Email
          };
  
          var result = await userManager.CreateAsync(newUser, user.PasswordHash);
  
          if (result.Succeeded) {
          ...
  </code></pre>
  <p><strong>Solution</strong></p>
  <p>There is NO changes to <em>IdentityConfig.cs</em>. Only changes is to my API Controller.</p>
  <pre><code>  // POST: api/auth/register
          [ActionName(&quot;Register&quot;)]
          public async Task&lt;HttpResponseMessage&gt; PostRegister(Auth user) {
  
  //Changed to the following line
              ApplicationUserManager userManager = HttpContext.Current.GetOwinContext().GetUserManager&lt;ApplicationUserManager&gt;();
  
              var newUser = new ApplicationUser {
                  UserName = user.Email,
                  Email = user.Email
              };
  
              var result = await userManager.CreateAsync(newUser, user.PasswordHash);
  </code></pre>