我在accountscontroller中具有以下代码:
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Products.Helpers;
using Products.Models;
using Products.ViewModels;
namespace Products.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AccountsController : Controller
{
private readonly ContextUsers _appDbContext;
private readonly UserManager<AppUser> _userManager;
private readonly IMapper _mapper;
public AccountsController(ContextUsers context,UserManager<AppUser> userManager,IMapper mapper)
{
_appDbContext = context;
_userManager = userManager;
_mapper = mapper;
}
[HttpPost]
public async Task<IActionResult> Post([FromBody]RegistrationViewModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var userIdentity = _mapper.Map<AppUser>(model);
var result = await _userManager.CreateAsync(userIdentity, model.Password);
if (!result.Succeeded) return new BadRequestObjectResult(Errors.AddErrorsToModelState(result, ModelState));
await _appDbContext.Customers.AddAsync(new Customer { IdentityId = userIdentity.Id, Location = model.Location });
await _appDbContext.SaveChangesAsync();
return new OkObjectResult("Account created");
}
}
}
我在Appuser类中有以下代码:
public class AppUser : IdentityUser
{
// Extended Properties
public string FirstName { get; set; }
public string LastName { get; set; }
public long? FacebookId { get; set; }
public string PictureUrl { get; set; }
}
和以下客户类:
public class Customer
{
public int Id { get; set; }
public string IdentityId { get; set; }
public AppUser Identity { get; set; } // navigation property
public string Location { get; set; }
public string Locale { get; set; }
public string Gender { get; set; }
}
当我在Postman中提出邮政请求时,我会收到以下错误:
InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager`1[Products.Models.AppUser]' while attempting to activate 'Products.Controllers.AccountsController'.
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)
我正在尝试创建用户,但是当我提出邮政请求时,我甚至都不会输入控制器,所以我无法调试
从startup.cs配置方法:
public void ConfigureServices(IServiceCollection services)
{
.AddCors(o => o.AddPolicy("AllowAllOrigins", builder =>
{
builder.AllowAnyMethod()
.AllowAnyHeader()
.AllowAnyOrigin();
}));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddDbContext<Context>(options =>
options.UseSqlServer(Configuration.GetConnectionString("LaprDB")));
services.AddDbContext<ContextUsers>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MyDbConnection")));
services.AddHostedService<TimedHostedService>();
services.AddAutoMapper();
}
您缺少一条线将身份对象添加到DI容器中。您需要调用AddDefaultIdentity
方法。将此行添加到Startup
类中的ConfigureServices
方法:
services.AddDefaultIdentity<AppUser>()
.AddEntityFrameworkStores<ContextUsers>();
有关设置身份的更多信息,请参见此处。