Ant Ant - 1 month ago 9
ASP.NET (C#) Question

How to prevent users registering with specific usernames?

I'm using the ASP.NET authentication methods and I want to prevent my users from registering with certain usernames. How do I prevent that from happening?

Is there a method built-in to blacklist the registration of certain usernames, or is it best to just write some checks in the Register method in the controller to prevent registration if they match any usernames in a list?

Answer
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {

// ************ Check the username aganist the list ***********
        var user = new ApplicationUser() { UserName = model.UserName };
        var result = await UserManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            await SignInAsync(user, isPersistent: false);
            return RedirectToAction("Index", "Home");
        }
        else
        {
            AddErrors(result);
        }
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

Hope this helps