Last active
February 19, 2021 15:26
-
-
Save fmshk97/b507575a10500a311d2d5409467868d4 to your computer and use it in GitHub Desktop.
AccountsController Implementation For Register API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Authentication.Apis.Models; | |
using Microsoft.AspNetCore.Identity; | |
using Microsoft.AspNetCore.Mvc; | |
using System; | |
using System.Linq; | |
using System.Threading.Tasks; | |
namespace Authentication.Apis.Controllers | |
{ | |
[Route("[controller]/[action]")] | |
[ApiController] | |
public class AccountsController : Controller | |
{ | |
private readonly UserManager<AppUser> _userManager; | |
public AccountsController(UserManager<AppUser> userManager) | |
{ | |
_userManager = userManager; | |
} | |
[HttpPost] | |
public async Task<IActionResult> Register([FromBody] RegistrationInputModel registrationInput) | |
{ | |
var user = await _userManager.FindByNameAsync(registrationInput.UserName); | |
if (user != null) | |
{ | |
return BadRequest("User already exists."); | |
} | |
user = new AppUser | |
{ | |
Id = Guid.NewGuid().ToString(), | |
UserName = registrationInput.UserName, | |
Email = registrationInput.Email | |
}; | |
var result = await _userManager.CreateAsync(user, registrationInput.Password); | |
if (!result.Succeeded) | |
{ | |
var resultErrors = result.Errors.Select(e => e.Description); | |
return BadRequest(string.Join("\n", resultErrors)); | |
} | |
return Ok(user); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment