Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/268.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 我是否应该将User.Identity.GetUserId()返回的值转换为GUID?_C#_Asp.net_Asp.net Identity - Fatal编程技术网

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。空的和进一步的逻辑将中断。我的代码做完全相同的事情,它只是避免需要命名和保留返回值。