Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can the Identity.GetUserId() be made to return a Guid instead of a string?

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?

like image 854
Alan2 Avatar asked Apr 05 '15 17:04

Alan2


2 Answers

A guid can take a string as a constructor

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

like image 164
ste-fu Avatar answered Nov 13 '22 08:11

ste-fu


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()
like image 38
Amir Avatar answered Nov 13 '22 08:11

Amir