[Route("api/[controller]")] [ApiController] public class AuthenticationController : ControllerBase { private readonly UserManager<AppUser> _userManager; private readonly IRepository _repository; private readonly IUserClaimsPrincipalFactory<AppUser> _claimsPrincipalFactory; private readonly IConfiguration _configuration; public AuthenticationController(UserManager<AppUser> userManager, IUserClaimsPrincipalFactory<AppUser> claimsPrincipalFactory, IConfiguration configuration, IRepository repository) { _userManager = userManager; _claimsPrincipalFactory = claimsPrincipalFactory; _configuration = configuration; _repository = repository; } [HttpPost] [Route("RegisterUser")] public async Task<IActionResult>RegisterUser(UserViewModel uvm) { var user = await _userManager.FindByNameAsync(uvm.username); if (user == null) { try { string phoneNumberPattern = @"^0\d{9}$"; bool isValidPhoneNumber = Regex.IsMatch(uvm.phonenumber, phoneNumberPattern); if (!isValidPhoneNumber) return BadRequest("Please enter a valid 10-digit phone number"); user = new AppUser { Id= Guid.NewGuid().ToString(), UserName= uvm.username, Email= uvm.emailaddress, PhoneNumber= uvm.phonenumber }; var result= await _userManager.CreateAsync(user, uvm.password); if (result.Errors.Count() > 0) { StringBuilder errorlist = new StringBuilder("These registration errors need to be resolved"); foreach (var error in result.Errors) { errorlist.Append($"{error.Code}: {error.Description}"); } return BadRequest($"{errorlist}"); } } catch (Exception ex) { return StatusCode(StatusCodes.Status500InternalServerError, $"Error occured{ex.Message}"); } } else { return Conflict($"The username '{uvm.username}' already exists. Please use a different username"); } return Ok($"Your account '{uvm.username}' was created successfully. You may proceed with logging in"); } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter