Jepzen
Jepzen

Reputation: 3162

User.Identity.GetUserId() return null

Based on this article and the source code in github associated with this tutorial I am trying to implement a mvc application where users have individual resources.

I have the authorize attribute on my controller and if I am not logged in I will be redirected to the login page. I can see my user name on the top of the page so I assume things are fine. But then I try a create action on another controller and finds that currentUser is null.

This seem to happen in a random way which makes it very frustrating. But lately only failing.

Could it be something with creation of the database? I'm using Code First.

 [Authorize]
public class ShopsController : Controller
{
    private ApplicationDbContext db;
    private UserManager<ApplicationUser> manager;

    public ShopsController()
    {
        db = new ApplicationDbContext();
        manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));

    }


    // GET: Shops
    public ActionResult Index()
    {
        var currentUser = manager.FindById(User.Identity.GetUserId());
        var shops = db.Shops.ToList().Where(shop => shop.Owner.Id == currentUser.Id);
        return View(shops);
    }

Upvotes: 1

Views: 2785

Answers (1)

N_E
N_E

Reputation: 787

try this code (Note: the cast to string):

 User.Identity.GetUserId<string>()

since my ID column in database was Id nvarchar(128),not null without cast i was receiving null but after cast it was giving me the expected GUID

Upvotes: 2

Related Questions