C# 我是否应该将User.Identity.GetUserId()返回的值转换为GUID?
我创建了以下类:C# 我是否应该将User.Identity.GetUserId()返回的值转换为GUID?,c#,asp.net,asp.net-identity,C#,Asp.net,Asp.net Identity,我创建了以下类: public class Config { public Guid UserId { get; set; } public string AdminJSON { get; set; } public string UserJSON { get; set; } } 当我查询我正在使用的数据时: Config config = await db.Configs.FindAsync(User.Identity.GetUserId()); 这是查找的正确方法
public class Config
{
public Guid UserId { get; set; }
public string AdminJSON { get; set; }
public string UserJSON { get; set; }
}
当我查询我正在使用的数据时:
Config config = await db.Configs.FindAsync(User.Identity.GetUserId());
这是查找的正确方法吗。似乎User.Identity.GetUserId返回一个
一串我是否应该强制转换此以返回GUID
我还有另一个问题:
UserId = User.Identity.GetUserId()
这也失败了。我试图通过在User.Identity.GetUserId之前添加Guid来执行强制转换,但这会显示一条消息,说明错误1无法将类型“string”转换为“System.Guid”
它会出错,因为它不能您需要使用Guid.ParseUser.Identity.GetUserId或更好的防故障方法
Guid userId;
bool worked=Guid.TryParse(User.Identity.GetUserId(),out userId);
if(worked)
{
//go ahead
}
else
{
throw new Exception("Invalid userid");
}
转换为比第三方库提供给您的类型更严格的类型似乎不是一个好主意。仅出于这个原因,我就将UserId保留为字符串。如果您发现它成为一个性能问题,您随时可以在以后对其进行优化 如果您刚开始使用asp.net Identity,我强烈建议您使用默认项目,因为它已经连接好了 以下是一些在我刚开始时帮助我的文章:
我将省略工作变量,只需执行if Guid.TryParseUser.Identity.GetUserId,out userId{…}如果Guid无效,则不能继续。否则它将是Guid。空的和进一步的逻辑将中断。我的代码做完全相同的事情,它只是避免需要命名和保留返回值。