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;
}
If you are asking if you should:
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.
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.