5

I am using ASP.Net Identity 2 but soon hope to change to Identity 3 when it becomes more stable (anyone know when that might be?). Here's a sample of my code:

content.ModifiedBy = User.Identity.GetUserId();

The Content table stores ModifedBy as a UNIQUEIDENTIFIER and the Content object assigns a datatype of Guid to ModifiedBy

When I look at the signature for GetUserId() it returns a string.

So how can I take the users UserId and put it into the ModifiedBy which is a Guid?

Alan2
  • 19,668
  • 67
  • 204
  • 365
  • This is because UserId can be not only a guid, so you need to convert yourself if you are sure that you use only guids. Identity V3 is for ASP.NET 5, so expect v3 released around the same time as the new ASP.NET. – trailmax Apr 06 '15 at 10:31

2 Answers2

8

A guid can take a string as a constructor

content.ModifiedBy = new Guid( User.Identity.GetUserId());

ste-fu
  • 6,003
  • 3
  • 26
  • 44
  • 3
    I would go with this approach. There is a generic version `GetUserId`, but underneath it uses `Convert.ChangeType` which requires the value argument to implement `IConvertible` which `Guid` doesn't. – MotoSV Apr 05 '15 at 18:18
4

You can use Guid.Parse() or Guid.TryParse()

content.ModifiedBy = Guid.Parse(User.Identity.GetUserId());

https://msdn.microsoft.com/en-us/library/system.guid.parse%28v=vs.110%29.aspx

As I was using same method over and over I added the following extension:

 public static class ExtensionMethods
{
    public static Guid ToGuid(this string value)
    {
        Guid result= Guid.Empty;
        Guid.TryParse(value, out result);
        return result;          
    }
}

and then I used this:

User.Identity.GetUserId().ToGuid()
Amir
  • 1,200
  • 13
  • 15