Asp.net mvc MVC-InvalidOperationException:找不到用户ID

Asp.net mvc MVC-InvalidOperationException:找不到用户ID,asp.net-mvc,authentication,Asp.net Mvc,Authentication,当我使用以下代码注册用户时: // POST: /Account/Register [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser() { Us

当我使用以下代码注册用户时:

// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser() { UserName = model.UserName };

        IdentityResult result = await UserManager.CreateAsync(user, model.Password);

        if (result.Succeeded)
        {
            await SignInAsync(user, isPersistent: false);
            return RedirectToAction("Index", "Home");
        }
        else
        {
            AddErrors(result);
        }

        return View(model);
    }
}
我没有添加UserID,并且在用户类(其Id)或AspNetUsers表中没有UserID字段。 该表中存在该用户,但同样没有用户ID

我已尝试清除cookies等,但仍然没有成功重新登录。 我把收银机弄错了吗?我不明白为什么身份验证要查找UserId字段,而它似乎不存在

编辑: 当我第一次登录时…我会看到错误页面。但是,当我重新打开页面并读取cookie时,我可以访问所有内容。初次登录到底是怎么回事

以下是SignInAsync方法:

 private async Task SignInAsync(ApplicationUser user, bool isPersistent)
        {
            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
            var _identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

            AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, _identity);
        }
包容

 public class ApplicationUser : IdentityUser
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
    }
公共类应用程序用户:IdentityUser
{
公共异步任务GenerateUserIdentityAsync(用户管理器)
{
//注意authenticationType必须与CookieAuthenticationOptions.authenticationType中定义的类型匹配
var userIdentity=wait manager.CreateIdentityAsync(这是DefaultAuthenticationTypes.ApplicationOkie);
//在此处添加自定义用户声明
返回用户身份;
}
}

编辑:我错了,你提到了Dapper,因此Dapper特定的细节并不相关,但修复的总体思路仍然是——你的Id和UserId列可能没有正确匹配


我昨天遇到了这个错误。我想您之前提到过,您正在使用Dapper作为数据访问机制。我认为这可能是相关的,因为您还提到表有一个
Userid
字段,但是您的用户类有一个
Id
属性。我猜,如果
Id
属性中没有新的
Guid
,那么您可能还需要一些代码来为该属性分配一个新的
Guid
。大概是这样的:

public ApplicationUser()
{
    Id = Guid.NewGuid().ToString();
}
这与简洁映射的工作方式相结合可能会让您感到困惑,因为
Id
字段将以新的
Guid
结束,而不是从表中读取的Guid

在下面的示例中,Dapper无法分配
ApplicationUser
的Id字段,因为DB字段的名称与类的属性不同。但它已经从构造函数中获得了一个Id值。这会导致以后调用
FindByIdAsync()
和friends失败

public async Task<ApplicationUser> FindByNameAsync(string userName)
{
    ApplicationUser result = null;

    using (var conn = await GetOpenDBConnection())
    {
        try
        {
            // this query is bugged with Dapper because UserId does not
            // exist on ApplicationUser.
            var queryResults = await conn.QueryAsync<ApplicationUser>(
                "SELECT UserId, UserName, Email FROM dbo.Users WHERE UserName = @UserName;",
                new { UserName = userName });

            result = queryResults.FirstOrDefault();
        }
        catch (Exception ex)
        {
                            //handle error appropriately.
            result = null;
        }
    }

    return result;
}

公共异步任务,了解如何以非常干净的方式映射简洁的字段。

能否共享您的用户模型?该用户是IPrinicipal实现。我想是烤熟了。用户对象是一个标识符,你能给我们展示一下方法SignInAsync(user,isPersistent:false)的实现吗;?补充。谢谢你的帮助,all@rigamonk-您正在显示两个不同的
CreateIdentityAsync
。你指的是哪一个?您还应该显示您的
应用程序用户
的外观,因为它可能与此相关。
public async Task<ApplicationUser> FindByNameAsync(string userName)
{
    ApplicationUser result = null;

    using (var conn = await GetOpenDBConnection())
    {
        try
        {
            // this query is bugged with Dapper because UserId does not
            // exist on ApplicationUser.
            var queryResults = await conn.QueryAsync<ApplicationUser>(
                "SELECT UserId, UserName, Email FROM dbo.Users WHERE UserName = @UserName;",
                new { UserName = userName });

            result = queryResults.FirstOrDefault();
        }
        catch (Exception ex)
        {
                            //handle error appropriately.
            result = null;
        }
    }

    return result;
}