1

The following controller should create a user within the local SQL Server database, but when refreshing the dbo.AspNetUsers table, there are no users found. What am I missing here?

UserController.cs

using System.Threading.Tasks;
using backend.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;

namespace backend.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UserController : Controller
    {
        private readonly UserManager<AppUser> userManager;

        public UserController(UserManager<AppUser> usrMgr)
        {
            userManager = usrMgr;
        }

        [HttpPost]
        public async Task<IActionResult> Register([FromBody]CreateUserModel model)
        {
            AppUser user = new AppUser
            {
                UserName = model.Email,
                Email = model.Email
            };
            var result = await userManager.CreateAsync(user, model.Password);

            return CreatedAtAction(nameof(Register), user);
        }
    }
}

Postman returns the following 201 Created body:

{
    "id": "random string of characters here",
    "userName": "[email protected]",
    "normalizedUserName": null,
    "email": "[email protected]",
    "normalizedEmail": null,
    "emailConfirmed": false,
    "passwordHash": null,
    "securityStamp": null,
    "concurrencyStamp": ""random string of characters here",
    "phoneNumber": null,
    "phoneNumberConfirmed": false,
    "twoFactorEnabled": false,
    "lockoutEnd": null,
    "lockoutEnabled": false,
    "accessFailedCount": 0
}

Solution

After using the answer by Volodymyr Bilyachat, the failed result object passed to Postman revealed that the test password that I was using was too weak. I then knew to add the following password settings to Startup.cs, and to choose a password that would work.

services.Configure<IdentityOptions>(options =>
            {
                // Password settings.
                options.Password.RequireDigit = true;
                options.Password.RequireLowercase = true;
                options.Password.RequireNonAlphanumeric = true;
                options.Password.RequireUppercase = true;
                options.Password.RequiredLength = 6;
                options.Password.RequiredUniqueChars = 1;

                // Lockout settings.
                options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
                options.Lockout.MaxFailedAccessAttempts = 5;
                options.Lockout.AllowedForNewUsers = true;

                // User settings.
                options.User.AllowedUserNameCharacters =
                "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
                options.User.RequireUniqueEmail = false;
            });
4
  • 200 or 200+ messages mean success. 201 mean your user is created. Did you check your database? There must be an entry in AspNetUser table. Commented May 14, 2019 at 0:26
  • Confusing right! I checked the database as explained above, hit refresh, and even restarted Visual Studio 2019. Commented May 14, 2019 at 0:28
  • user possible errors: check if you are connected with the right database? Make sure you are checking AspNetUser table in the correct database. Check the dbcontext connection string. One more thing, put your code inside Try Catch block, and check if there any exception. Commented May 14, 2019 at 0:28
  • Can you share your string connection without credentials? Commented May 14, 2019 at 0:31

1 Answer 1

1

You need to check result

var result = await userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
    return CreatedAtAction(nameof(Register), user);
}
// handle bad request

so it can be that result contains error code.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.