简体   繁体   English

ASP.NET 核心 - AutoMapper.AutoMapperMappingException:缺少类型 map 配置或不支持的映射

[英]ASP.NET Core - AutoMapper.AutoMapperMappingException: Missing type map configuration or unsupported mapping

In my ASP.NET Core Web API, I have IdentityDbContext:在我的 ASP.NET 核心 Web API 中,我有 IdentityDbContext:

public class MyDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, long, IdentityUserClaim<long>, ApplicationUserRole, IdentityUserLogin<long>, IdentityRoleClaim<long>, IdentityUserToken<long>>
{
    public MyDbContext(DbContextOptions<MyDbContext> options)
        : base(options)
    {
    }

    public DbSet<ApplicationRole> ApplicationRole { get; set; }
    public DbSet<ApplicationUserRole> ApplicationUserRole { get; set; }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        builder.Entity<ApplicationUser>(entity =>
        {
            entity.Property(u => u.Id).ValueGeneratedOnAdd();
            entity.HasIndex(u => u.Email).IsUnique();
            entity.HasIndex(u => u.UserName).IsUnique();
        });
        builder.Entity<ApplicationRole>(entity =>
        {
            entity.Property(r => r.Id).ValueGeneratedOnAdd();
            entity.HasIndex(r => r.Name).IsUnique();
        });
}

IdentityModel:身份模型:

 public class ApplicationUser : IdentityUser<long>
 {
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string MobileNumber { get; set; }

    [JsonIgnore]
    public bool? IsDeleted { get; set; }
    public DateTime? LastLogin { get; set; }
    public ICollection<ApplicationUserRole> UserRoles { get; set; }
 }

 public class ApplicationRole : IdentityRole<long>
 {
    public ICollection<ApplicationUserRole> UserRoles { get; set; }
 }

 public class ApplicationUserRole : IdentityUserRole<long>
 {
    public override long UserId { get; set; }
    public override long RoleId { get; set; }
    public virtual ApplicationUser User { get; set; }
    public virtual ApplicationRole Role { get; set; }
 }
} 

LoginRequestDto:登录请求Dto:

public class LoginRequestDto
{
    [Required]
    [JsonProperty(PropertyName = "username")]
    public string UserName { get; set; }

    [Required(ErrorMessage = "The password is required!")]
    public string Password { get; set; }
}

UserDto:用户Dto:

public class UserDto
{
    public long Id { get; set; }
    public string Firstname { get; set; }
    public string Lastname { get; set; }
    public string Email { get; set; }
    public string UserName { get; set; }
    public string MobileNumber { get; set; }
    public DateTime LastLogin { get; set; }
}

AuthMapper:授权映射器:

public class AuthMapperProfile : Profile
{
    public AuthMapperProfile()
    {
        CreateMap<ApplicationUser, UserDto>();

}

Services:服务:

public interface IAuthService
{
    Task<GenericResponseDto<object>> LoginUser(LoginRequestDto request);
}

public class AuthService : IAuthService
{
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly RoleManager<ApplicationRole> _roleManager;
    private readonly IConfiguration _configuration;
    private readonly IMapper _mapper;
    private readonly MyDbContext _context;

    public AuthService(
        UserManager<ApplicationUser> userManager,
        RoleManager<ApplicationRole> roleManager,
        IConfiguration configuration,
        IMapper mapper,
        MyDbContext context

    )
    {
        _userManager = userManager;
        _roleManager = roleManager;
        _configuration = configuration;
        _mapper = mapper;
        _context = context;
    }

    public async Task<GenericResponseDto<object>> LoginUser(LoginRequestDto request)
    {
        var user = await _userManager.FindByNameAsync(request.UserName);
        var response = new GenericResponseDto<object>();

        if (user != null && await _userManager.CheckPasswordAsync(user, request.Password))
        {
            var roles = await _userManager.GetRolesAsync(user);
            var authClaims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, user.UserName),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
            };
            foreach (var userRole in roles)
            {
                authClaims.Add(new Claim(ClaimTypes.Role, userRole));
            }
            var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:Secret"]));
            var token = new JwtSecurityToken(
                issuer: _configuration["JWT:ValidIssuer"],
                audience: _configuration["JWT:ValidAudience"],
                expires: DateTime.Now.AddHours(3),
                claims: authClaims,
                signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256)
            );

            response.Result = new
            {
                token = new JwtSecurityTokenHandler().WriteToken(token),
                user = _mapper.Map<UserDto>(user),
                expires = token.ValidTo
            };
            response.StatusCode = 200;
            user.LastLogin = DateTime.Now;
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                response.Error = new ErrorResponseDto() { ErrorCode = 500, Message = ex.Message };
            }
            return response;
        }

        response.StatusCode = 400;
        response.Error = new ErrorResponseDto { ErrorCode = 400, Message = "Invalid Username or Password!" };

        return response;
    }
}

I got this error:我收到了这个错误:

AutoMapper.AutoMapperMappingException: Missing type map configuration or unsupported mapping. AutoMapper.AutoMapperMappingException:缺少类型 map 配置或不支持的映射。

Mapping types: Object -> UserDto System.Object -> DDM.API.Core.DTOs.v1.Authentication.UserDto at lambda_method198(Closure, Object, UserDto, ResolutionContext ) at DDM.API.Core.Services.v1.Concrete.AuthService.LoginUser(LoginRequestDto request) in C:\Users\MyApp\Core\Services\v1\Concrete\AuthService.cs:line 78 Mapping types: Object -> UserDto System.Object -> DDM.API.Core.DTOs.v1.Authentication.UserDto at lambda_method198(Closure, Object, UserDto, ResolutionContext ) at DDM.API.Core.Services.v1.Concrete.AuthService .LoginUser(LoginRequestDto request) 在 C:\Users\MyApp\Core\Services\v1\Concrete\AuthService.cs:line 78

This is line 78:这是第 78 行:

response.Result = new response.Result = 新的

startup.cs:启动.cs:

  // Auto mapper
  services.AddAutoMapper(typeof(Startup));

  // Dependency Injection
  services.AddScoped<IAuthService, AuthService>();

controller: controller:

    [Produces("application/json")]
    [HttpPost("login")]
    public async Task<ActionResult<GenericResponseDto<object>>> Login(LoginRequestDto loginRequest)
    {
        var response = await _authService.LoginUser(loginRequest);
        Response.StatusCode = response.StatusCode ?? StatusCodes.Status200OK;
        return new JsonResult(response);
    }

What do I do to resolve this?我该怎么做才能解决这个问题?

Thanks谢谢

For some reason, your mapping Profile is not taken into account, the error message supports this, the error message says Automapper uses mapping of Object to UserDto, instead of ApplicationUser to UserDto.由于某种原因,您的映射Profile没有被考虑在内,错误消息支持这一点,错误消息说 Automapper 使用 Object 到 UserDto 的映射,而不是 ApplicationUser 到 UserDto。

Try configure the mapper in an alternate way尝试以另一种方式配置映射器

var config = new MapperConfiguration(cfg => {
    cfg.AddMaps(myAssembly);
});

IMapper mapper = config.CreateMapper();

services.AddSingleton(mapper);

Another option, try mapping manually另一种选择,尝试手动映射

var config = new MapperConfiguration(cfg => {
    cfg.CreateMap<ApplicationUser, UserDto>();
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 AutoMapper.AutoMapperMappingException:缺少类型 map 配置或 .NET CORE 中不支持的映射 - AutoMapper.AutoMapperMappingException: Missing type map configuration or unsupported mapping in .NET CORE Asp.net 核心 3.1 AutoMapperMappingException:缺少类型 map 配置或不支持的映射 - Asp.net core 3.1 AutoMapperMappingException: Missing type map configuration or unsupported mapping ASP.net AutoMapper 缺少类型映射配置或不受支持的映射 - ASP.net AutoMapper Missing type map configuration or unsupported mapping AutoMapper 9.0:AutoMapperMappingException:“缺少类型 map 配置或不支持的映射。” - AutoMapper 9.0 : AutoMapperMappingException: 'Missing type map configuration or unsupported mapping.' AutoMapperMappingException - 缺少类型映射配置或不支持的映射 - AutoMapperMappingException - Missing type map configuration or unsupported mapping .Net Core Automapper 缺少类型 map 配置或不支持的映射 - .Net Core Automapper missing type map configuration or unsupported mapping 库中的 AutoMapper 配置文件类 - AutoMapperMappingException:缺少类型映射配置或不支持的映射错误 - AutoMapper profile class in library - AutoMapperMappingException: Missing type map configuration or unsupported mapping error 缺少类型映射配置或不受支持的映射AutoMapper - Missing Type Map Configuration Or Unsupported Mapping AutoMapper Automapper:缺少类型映射配置或不受支持的映射 - Automapper: Missing type map configuration or unsupported mapping Automapper:“缺少类型映射配置或不受支持的映射” - Automapper: “Missing type map configuration or unsupported mapping”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM