For years I have worked with C # systems in WebForms , but by necessity I have migrated my development goal to mobile applications with Xamarin and MVVM .
Now in parallel I'm developing web systems again, but in MVC standards. But one a doubt is haunting me ...
In WebForms, I have always used Session to treat the user logged in by MasterPage¹ . Now in MVC, where Filters and Roles are basic elements of a good project, what is the best way to store logged-in user data? Because I need to load the logged user data in the View and I also need the data to save records in the bank and etc.
Currently I'm using a filter to check the state of the session, and I'm still fortunately / unfortunately using Session to save your data and manipulate them, however, as everyone knows Session's depending on how much users logged in, end up consuming lots of server resources.
How to do it? Do I keep the Session's? I use Cookie? TempData? ViewBag? or other ...
¹ In a WebForms application I had a class for example: UserList, which contained the data of UserId, Name, Email, Photo etc.
I performed checks on PageLoad from MasterPage simply by using:
if(UsuarioLogado.UsuarioId < 1)
Response.Redirect("~/Login");
² In current applications in MVC, I also use a class to save user data: Below, I use a class to pass the data I consulted in the database to save to the Session:
private void SessionAdd(Usuario dados)
{
System.Web.HttpContext.Current.Session.Add("UsuarioId", dados.UsuarioId);
}
I also use a Filter IAuthorizationFilter
that does the following:
public void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)
|| filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
{
return;
}
if (filterContext.HttpContext.Session != null && filterContext.HttpContext.Session["UsuarioId"] == null)
{
filterContext.HttpContext.Response.Redirect("~/Login/Acesso");
}
}
When I need the data to display in the View, I simply @Session["Nome"]
.
My applications are working, but I believe that the way I do the manipulation works well for only a few logged-in users, but it's not the best way for many users.