using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using UsuariosApi.Data; using UsuariosApi.Models;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
var connString = builder.Configuration.GetConnectionString("UsuarioConnection");
builder.Services.AddDbContext (opts => { opts.UseMySql(connString, ServerVersion.AutoDetect (connString)); });
builder.Services .AddIdentity<Usuario, IdentityRole>() .AddEntityFrameworkStores() .AddDefaultTokenProviders();
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); }
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
--------------------------------------------------------------------------------------------------------------
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore; using UsuariosApi.Models;
namespace UsuariosApi.Data { public class UsuarioDbContext : IdentityDbContext { public UsuarioDbContext(DbContextOptions opts) : base(opts) { } } }
----------------------------------------------------------------------------------------
using AutoMapper;
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using UsuariosApi.Data.Dtos; using UsuariosApi.Models;
public class UsuarioController : ControllerBase { private IMapper _mapper; private UserManager _userManager;
public UsuarioController(IMapper mapper, UserManager<Usuario> userManager)
{
_mapper = mapper;
_userManager = userManager;
}
[HttpPost]
public async Task<IActionResult> CadastraUsuario
(CreateUsuarioDto dto)
{
Usuario usuario = _mapper.Map<Usuario>(dto);
IdentityResult resultado = await _userManager.CreateAsync(usuario, dto.Password);
if(resultado.Succeeded) return Ok("Falha ao cadastrar usuário!");
throw new ApplicationException("Falha ao cadastrar usuário!");
}
}
----------------------------------------------------------------------------
using System;
using Microsoft.AspNetCore.Identity;
namespace UsuariosApi.Models { public class Usuario : IdentityUser { public DateTime DataNascimento { get; set; } public Usuario() : base() { } } }