Reputation: 2270
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
}
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;
});
Upvotes: 1
Views: 128
Reputation: 19484
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.
Upvotes: 1