简体   繁体   中英

Should I cast the value returned from User.Identity.GetUserId() to make it a GUID?

I created the following class:

public class Config
{
    public Guid UserId { get; set; }
    public string AdminJSON { get; set; }
    public string UserJSON { get; set; }
}

When I query the data I am using:

Config config = await db.Configs.FindAsync(User.Identity.GetUserId());

Is this the correct way to do the find. It seems that User.Identity.GetUserId() returns a string. Should I be casting this to return a GUID.

I also have another problem with this:

UserId = User.Identity.GetUserId()   

This also fails. I tried to do a cast by adding (Guid) before the User.Identity.GetUserId() however this gives a message saying Error 1 Cannot convert type 'string' to 'System.Guid'

It errors out as it cannot

You need to use Guid.Parse(User.Identity.GetUserId()) or better fail proof method

Guid userId;
bool worked=Guid.TryParse(User.Identity.GetUserId(),out userId);
if(worked) 
{
    //go ahead
}
else 
{
    throw new Exception("Invalid userid"); 
}

It seems like a bad idea to convert to a type that is stricter than that handed to you by a third party library. For this reason alone I would keep UserId as a string. If you find it becomes a performance problem you can always optimize it later.

If you're just starting out with asp.net Identity I would strongly suggest using a default project as it is already wired up.

Here are some articles that helped me when I first got started:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM