Reputation: 757
Currently I have a problem that I need to solve to avoid duplicate code in my software. I would like that by the time the login was performed, the system would store some information so that I did not have to go all the time in the query database. I would need to store, for example, information from two classes:
USER
public class User
{
public Guid Id { get; set; }
public String Name { get; set; }
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
}
SCHOOL
public class School
{
public Guid Id { get; set; }
public String Name { get; set; }
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
public int Code { get; set; }
}
I constantly use information from these two in my software, and currently every time I load them from the database. So I would like to know if there is a way for me to store the information at the time I log in so that I do not have to query the database. My login code:
if (user != null)
{
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(new FormsAuthenticationTicket(login.Email.ToLower(), false, 60))));
//Store school and user information here.
return RedirectToAction("Dashboard", "Home", new { area = "" });
}
Is there any way to store this information and retrieve them the same as the User.Identity.Name
, for example?
Upvotes: 1
Views: 64
Reputation: 573
there are many different solution for your requirement:
Caching
You can use in memory cache (like asp.net cache) if your app is running on one server. If more than one then you can use a distributed cache something like Redis, or Memcached. You can also get some free online server for test purposes as well. If you choose caching you need a good strategy to invalidate the cache as well because cache without a good invalidation strategy can be very destructive for your application.
No SQL databases
Another solution is No SQL databases which are much faster than relational databases.
Web storage
If your data is not sensitive, you can store a small amount of data in web storage of the browser for each user with some considerations.
Upvotes: 1
Reputation: 103
You could use the Session
Object
https://learn.microsoft.com/en-us/dotnet/api/system.web.mvc.controller.session?view=aspnet-mvc-5.2
https://code.msdn.microsoft.com/How-to-create-and-access-447ada98
This object allow you to use the information of a User in multiple controllers. It also allows you to add to it an expired type. By default it's 30min.
Upvotes: 0
Reputation: 949
Use session, after login set
Session["user"] = user;
Session["school"] = school;
and then use it wherever you want How to use sessions in an ASP.NET MVC 4 application?
Upvotes: 0