0

I have to get the user id from my database to do most of the functions in my application. I have .net core 2.1 application with windows authentication enabled.

My question is which is efficient way, is it to request User.Identity.Name to check the loggeduser name and get the user id (with db query) or get the username from User.Identity.Name for the first time, query the id and assign it to session and use the id to subsequent request.

User user = new User(xDbContext);

if ((HttpContext.Session.GetInt32("CurrentUserId") == null))
{
    loggedUserId = userPrivilege.GetUserId(User.Identity.Name);
    HttpContext.Session.SetInt32("CurrentUserId", loggedUserId);
}
else
{
    loggedUserId = HttpContext.Session.GetInt32("CurrentUserId").Value;
}
tksdotnet1
  • 81
  • 6

1 Answers1

1

If you are asking if you should:

  1. Query your database every time you need the value, or
  2. Query the database once and store the value in Session so you have it the next time you need it

Then the answer is: it depends. If your Session data is stored in a database on a different server, then it won't make a difference. If your database is running on the same server as your site, then it will make very little difference.

If your database is on a different server and Session is stored in memory, then it will be much faster to retrieve the value from Session.

If your Session data is stored in a database, then another option is to use in-memory caching. But that data will be shared across all sessions, so you would have to make sure that one person's data isn't accessed in someone else's request.

Gabriel Luci
  • 38,328
  • 4
  • 55
  • 84
  • Thank you it make sense how you brought my question to clarity. How can I avoid my above code to be repeated in every action method. – tksdotnet1 Aug 21 '19 at 12:48
  • You can use middleware, which will run on each request before your action method does. There is an example of this in [this answer](https://stackoverflow.com/a/52547588/1202807) – Gabriel Luci Aug 21 '19 at 12:52