C# IsEmailConfirmedAsync具有一些无效参数
我正在使用C# IsEmailConfirmedAsync具有一些无效参数,c#,asp.net-mvc,asp.net-identity,C#,Asp.net Mvc,Asp.net Identity,我正在使用mvc5的scaffold-ed代码生成登录方法。我按照官方的教程从 …添加确保在用户登录系统之前确认电子邮件的附加功能 以下是我在控制器中的代码: [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid)
mvc5
的scaffold-ed代码生成登录方法。我按照官方的教程从
…添加确保在用户登录系统之前确认电子邮件的附加功能
以下是我在控制器中的代码:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
var currentUser = UserManager.FindByNameAsync(model.Email);
if (currentUser != null)
{
if (!await UserManager.IsEmailConfirmedAsync(currentUser.Id))
{
ViewBag.errorMessage = "You must have a confirmed email to log on.";
return View("Error");
}
}
// Other scaffolded implementations
}
[HttpPost]
[异名]
[ValidateAntiForgeryToken]
公共异步任务登录(LoginView模型,字符串返回URL)
{
如果(!ModelState.IsValid)
{
返回视图(模型);
}
var currentUser=UserManager.FindByNameAsync(model.Email);
如果(currentUser!=null)
{
如果(!wait UserManager.IsEmailConfirmedAsync(currentUser.Id))
{
ViewBag.errorMessage=“您必须有一封确认的电子邮件才能登录。”;
返回视图(“错误”);
}
}
//其他框架实现
}
但是,VisualStudio出现了一个错误,指出该参数对于方法IsEmailConfirmedAsync
无效。显然,我检查过,currentUser.Id
是int
数据类型,是System.Threading.Task
的Id
。如何解决此问题,使我传递的是用户Id
而不是任务Id
?这是因为在您的代码中,当前用户
被分配了从查找用户返回的任务
您应该等待该调用以获得所需的行为
var currentUser = await UserManager.FindByNameAsync(model.Email);
甚至连与OP链接的示例都是这样的
// Require the user to have a confirmed email before they can log on.
var user = await UserManager.FindByNameAsync(model.Email);
if (user != null)
{
if (!await UserManager.IsEmailConfirmedAsync(user.Id))
{
ViewBag.errorMessage = "You must have a confirmed email to log on.";
return View("Error");
}
}
试试currentUser.Result。@ChetanRanpariya不,您不应该访问.Result
。如果异步调用在您到达该行并尝试访问.Result
时尚未完成,该怎么办?为什么不等待UserManager.FindByNameAsync(model.Email)
的结果?您是对的@mason。要使用结果,应使用wait调用FindByNameAsync。使用model.Email是个好主意,但我认为作者希望首先检查电子邮件的存在。@Pow4Pow5,这是因为在您的代码currentUser
中分配了查找用户返回的任务。您应该等待该调用以获取所需的用户var currentUser=await UserManager.FindByNameAsync(model.Email)
我简直不敢相信我犯了一个愚蠢的错误,没有注意到丢失的wait
关键字。。谢谢你的回答!