В моем веб-API ASP.NET Core-6 у меня есть этот код:
Идентификация.ApplicationUser:
public class ApplicationUser: IdentityUser
{
public string MobileNumber { get; set; }
[DefaultValue(false)]
public bool? IsAdmin { get; set; }
}
Помощник:
public class ServiceResult<T>: ServiceResult
{
public T Data { get; set; }
public ServiceResult(T data)
{
Data = data;
}
public ServiceResult(T data, ServiceError error): base(error)
{
Data = data;
}
public ServiceResult(ServiceError error): base(error)
{
}
}
public class ServiceResult
{
public bool Successful => this.Error == null;
public ServiceError Error { get; set; }
public ServiceResult(ServiceError error)
{
if (error == null)
{
error = ServiceError.DefaultError;
}
Error = error;
}
public ServiceResult() { }
public static ServiceResult Failed(ServiceError error)
{
return new ServiceResult(error);
}
public static ServiceResult<T> Failed<T>(ServiceError error)
{
return new ServiceResult<T>(error);
}
public static ServiceResult<T> Failed<T>(T data, ServiceError error)
{
return new ServiceResult<T>(data, error);
}
public static ServiceResult<T> Success<T>(T data)
{
return new ServiceResult<T>(data);
}
}
Я использую ASP.NET IdentityDbContext.
Оболочка запроса:
public interface IRequestWrapper<T>: IRequest<ServiceResult<T>>
{
}
Оболочка обработчика запросов:
public interface IRequestHandlerWrapper<in TRequest, TResponse>: IRequestHandler<TRequest, ServiceResult<TResponse>>
where TRequest: IRequestWrapper<TResponse>
{
}
Затем ДТО:
public class AdminUserListDto: IRequest
{
public Guid 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 bool? IsAdmin { get; set; }
public void Register(TypeAdapterConfig config)
{
config.NewConfig<ApplicationUser, AdminUserListDto>();
}
}
Внедрение зависимости:
public static class DependencyInjection
{
public static IServiceCollection AddApplication(this IServiceCollection services)
{
// Register Application Health Checks
services.AddHealthChecks()
.AddCheck<ApplicationHealthCheck>(name: "MY API");
// Register Fluent Validation service
services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly());
// Register MediatR Services
services.AddMediatR(Assembly.GetExecutingAssembly());
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(UnhandledExceptionBehaviour<,>));
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehaviour<,>));
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(PerformanceBehaviour<,>));
return services;
}
}
Программа.cs:
var builder = WebApplication.CreateBuilder(args);
// Add library project references for DependencyInjection
builder.Services.AddApplication();
Команда CreateAdminUserCommand:
public class CreateAdminUserCommand: IRequestWrapper<AdminUserListDto>
{
public string UserName { get; set; }
public string Email { get; set; }
public string MobileNumber { get; set; }
public string Password { get; set; }
public bool? IsAdmin { get; set; }
}
CreateAdminUserCommandValidator:
public class CreateAdminUserCommandValidator: AbstractValidator<CreateAdminUserCommand>
{
public CreateAdminUserCommandValidator()
{
RuleFor(u => u.UserName)
.NotEmpty().WithMessage("User Name field is required. ERROR!");
RuleFor(u => u.MobileNumber)
.NotEmpty().WithMessage("Mobile Number field is required. ERROR!");
RuleFor(u => u.Email)
.NotEmpty().WithMessage("Email field is required. ERROR!");
RuleFor(u => u.Password)
.NotEmpty().WithMessage("Password field is required. ERROR!");
}
}
Наконец, у меня есть:
public class CreateAdminUserCommandHandler: IRequestHandlerWrapper<CreateAdminUserCommand, AdminUserListDto>
{
private readonly IMediator _mediator;
private readonly IAppDbContext _dbContext;
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<ApplicationRole> _roleManager;
public CreateAdminUserCommandHandler(IMediator mediator, IAppDbContext dbContext, UserManager<ApplicationUser> userManager, RoleManager<ApplicationRole> roleManager)
{
_mediator = mediator;
_dbContext = dbContext;
_userManager = userManager;
_roleManager = roleManager;
}
public async Task<ServiceResult<AdminUserListDto>> Handle(CreateAdminUserCommand request, CancellationToken cancellationToken)
{
var adminUser = new ApplicationUser()
{
MobileNumber = request.MobileNumber,
UserName = request.UserName,
Email = request.Email,
IsAdmin = request.IsAdmin
};
var result = await _userManager.CreateAsync(adminUser, request.Password);
return ServiceResult.Success(_mediator.Send<AdminUserListDto>(adminUser));
}
}
После успеха я ожидаю, что он вернется:
Админусерлистдто
Но я получил эту ошибку:
Аргумент 1: невозможно преобразовать Identity.ApplicationUser в MediatR.IRequest<Response.AdminUserListDto>.
Затем adminUser выделяется в:
вернуть ServiceResult.Success(_mediator.Send(adminUser));
Как решить эту проблему?
Спасибо
Решение проблемы
Вы, вероятно, путаете mediator
и mapper
. Что вам нужно:
return ServiceResult.Success(_mapper.Map<AdminUserListDto>(adminUser));
Комментариев нет:
Отправить комментарий