Search code examples
c#asp.net-corerazor

How to get the user language Id from database and declare it as global variable, to be called on need, in .NET Core?


Tools used:

  • Visual Studio 2022 Community edition
  • .NET Core 7.0
  • Razor pages

Explanation

To lower the number of calls to the database throughout the app, I want to create a global variable for the current user language id, the value of which will be set on users login.

Then this variable will be called on need on every page model, to define the UI language.

I declared a class for the global variable, but could not go further than here.

I can not get the current userId, nor call the database table...

Question

How can this be done properly?

The code

namespace MyApp.Models
{
    private readonly Models.ApplicationDbContext _context;

    public class Class
    {
        var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
        private int langId = _context.Languages.where(x=>x.UserId = userId).FirstOrDefault().Id;
        public int GetLangId 
        {
            get { return langId; }
            set { langId = value; }
        }       
    }
}

Solution

  • According to your description, the best way to achieve your requirement is storing the language id inside the cookie or session.

    You could get the language id when the user login in and put it inside the user claims or directly inside the cookie.

    Then you could directly use it instead of querying the database every time.

    Since this cookie(claims) will expire with the user credential, you doesn't need to consider writing the condition to check the value and query the database again.

    It just set one time when the user login and you could read it from the claims or directly from the request cookie based on how you store it.

    About how to directly store and use the cookie in razor page, you could refer to below sample:

    Store:

        public void OnGet()
        {
            HttpContext.Response.Cookies.Append("testid","test");
    
        }
    

    Get:

     public void OnGet()
     {
         if (HttpContext.Request.Cookies.TryGetValue("testid", out string cookieValue))
         {
             // Use your cookieValue
         }
     }
    

    Result:

    enter image description here