使用 int 键时输入字符串的格式错误

Input string was not in a correct format error on using int keys

首先,我想向您保证,我已经在 SO 上阅读了许多标题相似的帖子。

我已经创建了一个 ASP.NET MVC 项目并按照这篇文章将模板表的键更改为 int

http://www.asp.net/identity/overview/extensibility/change-primary-key-for-users-in-aspnet-identity

但是我在 StartUp.Auth.cs

的这一行中遇到运行时错误
getUserIdCallback: (id) => (id.GetUserId<int>()))

错误=System.FormatException:输入字符串的格式不正确。感谢任何帮助。

我知道这是一个迟到的回复。但对于将来可能会遇到这种情况的人:清除缓存或切换到其他浏览器。

虽然你在代码中将pk从string改为int并更新了Identity相关表,但cookie仍然是你使用字符串pks登录的那个。

要消除此错误,您需要清除您网站的 cookie。

Chrome: F12 -> 应用程序 -> 存储 -> Cookies -> 你的站点 -> 清除

我真的不想改变浏览器体验的味道。因此,就我而言,从 Chrome DevTools (F12) > Application > Clear Storage > 清除站点数据 修复了它。

我遇到了类似的问题,生病了或重置了我的缓存。我认为要么是我的 cookie 变得无效,要么是 cookie 发生了变化,并且由于某种原因它无法再被解析。

我在 GitHub 存储库问题中找到了解决方案: https://github.com/TypecastException/AspNet-Identity-2-With-Integer-Keys/issues/2#issuecomment-128280883

使用以下代码解决了我的问题

getUserIdCallback: (id) => GrabUserId(id))

public static int GrabUserId(System.Security.Claims.ClaimsIdentity claim)
{
    if (!int.TryParse(claim.GetUserId(), out int id))
        return 0;
    else
        return id;
}

当返回 0 时,它只是将您注销,因为它无法将您识别为用户。