tl;dr: is at the bottom ;)
Imagine that I have database with some notes. To show them to user, I use this method (Entity Framework here):
var allNotes = db.Notes.Where(x => AllowAccess(x.AuthorId, User.GetUserId())).ToList();
AllowAccess() is function that will decide if current user is authorized to see the note. "x.AuthorId" is variable that stores ID of owner of note.
Note: User.GetUserId() is method that returns id of current user. I use Asp.net identity 3 for authentication (all authentication code was generated by Visual Studio for me)
This is how this function currently looks like:
public bool AllowAccess(string dbID, string userIdFromController)
{
var userId = User.GetUserId();
if(userId == null && userIdFromController != null)
{
Trace.Write("-----------null userId");
}
else if (userId == null && userIdFromController == null)
{
Trace.Write("-----------null userId ");
}
else
{
Trace.Write("-----------OK userId ");
}
return dbID == User.GetUserId();
}
The problem is: "userId" variable sometimes contains user ID, sometimes not. I can't guess why is that happening. There is no rule: it simply sometimes equals null. I firstly thought that is problem with asp.net identity 3 and it sometimes fails, but no.
As you can see, my function gets second parameter called "userIdFromController". It is nearly the same as "userId", with one difference: I call User.GetUserId() directly from controller (as you can see in first piece code in this question).
You know what's happening? "userIdFromController" is always set correctly, "userId" sometimes not. I've set breakpoints inside all of "if statements" in AllowAccess function and from time to time the first one is called (second never, third most often).
TL;DR: So, summing up: "userId" and "userIdFromController" is the same, but the first one is created in AllowAccess function, the second: directly in controller that calls AllowAccess. "userIdFromController" works always,"userId" sometimes. Why is that happening?