1)我想讓用戶在ASP.MVC/Identity應用程序中更改他們的用戶名(電子郵件)等。使用FluentValidation我想檢查沒有其他用戶正在使用新的電子郵件。FluentValidation/MVC/ASP Identity:如何在驗證模型時獲取當前用戶ID?
在控制器中,我會使用User.Identity.GetUserId(),但在構建驗證規則時不可用。我如何檢索當前經過身份驗證的userId?
public class ManageUserViewModelValidator : AbstractValidator<ManageUserViewModel>
{
public ManageUserViewModelValidator()
{
RuleFor(e => e.UserName)
.NotEmpty()
.WithMessage("Måste ange din e-post adress.")
.EmailAddress()
.WithMessage("Ogiltig e-post adress.")
.Must((model, _) => UserMethods.IsUserNameAvailable(model.UserName, "userId???"))
.WithMessage("E-post adressen är upptagen.");
}
...
}
[FluentValidation.Attributes.Validator(typeof(ManageUserViewModelValidator))]
public class ManageUserViewModel
{
[Display(Name = "E-post*")]
public string UserName { get; set; }
...
}
2)什麼是最好的方式來存儲這種變化。現在,我使用AutoMapper:
public static void Update(this DbContext context, ManageUserViewModel model, string userId)
{
User user = context.Users.FirstOrDefault(e => e.Id.Equals(userId));
Mapper.CreateMap<ManageUserViewModel, TessinUser>();
Mapper.Map(model, user);
context.SaveChanges();
}
3)在我的頭我顯示當前登錄的使用User.Identity.GetUserName()
用戶,但我已經改變了名後,該文本不更新。我需要註銷並再次登錄才能更新。有沒有辦法讓ASP更新當前用戶?
謝謝我會嘗試更新()可能會解決我所有的問題。感謝您澄清映射配置的位置。 –
我已經使用UpdateAsync的所有步驟,但我User.Identity。GetUserName()沒有更新?這可以以某種方式強制嗎? –
你使用ajax更新用戶嗎? – gaurav