1

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); } 
3
  • Hmm I wonder if your models are out of sync with the db. Do you get this when you've updated your entity models? Commented May 14, 2015 at 12:12
  • 1
    Also, why are you calling manager.FindById and returning the user entity if you're only going use the ID in next query? Seems like pointless db call... Commented May 14, 2015 at 12:16
  • I can usually get it to work by making sure i log out, close the solution, delete the database. I found out i was deleting the database every time in initiliazer. This i changed to DropCreateDatabaseIfModelChanges. About the other comment, have not thought about that, just using the sample code, get things to work, then hopefully understand it. Commented May 14, 2015 at 12:23

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.