我应该转换从User.Identity.GetUserId()返回的值以使其成为GUID吗?



我创建了以下类:

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无法将类型"字符串"转换为"系统"。Guid '

显示错误

您需要使用Guid.Parse(User.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,我强烈建议使用默认项目,因为它已经连接好了。

以下是一些在我刚开始写作时对我有帮助的文章:

  • http://www.codeproject.com/Articles/674760/Code-First-Migration-and-Extending-Identity-Accoun
  • http://www.asp.net/mvc/tutorials/mvc-5/create-an-aspnet-mvc-5-app-with-facebook-and-google-oauth2-and-openid-sign-on

最新更新