1
For years I worked with c# systems in Webforms, however, by necessity I migrated my development goal to mobile applications with Xamarin and standards MVVM.
Now in parallel I am developing again WEB systems however, in MVC standards. But a doubt has been chasing me...
In Webforms, I have always used Session to treat the user logged in by Masterpage¹. Now on MVC, where Filters and Roles are basic items of a good project, what is the best way to store the logged user data? Because I need to upload the user data logged in the View and also need the data to save records in the database and etc.
I am currently using a filter to check the session status, and I am still fortunately/unfortunately using Session to save² your data and manipulate it, however, as everyone knows the Session’s depending on the amount of logged in users, ends up consuming many server resources.
How to do it? I maintain Session’s? Use Cookie? Tempdata? Viewbag? or other...
¹ In a Webforms application I had a class for ex: User, which contained the data of User, Name, Email, Photo etc.
I performed the checks on Masterpage’s Pageload simply using:
if(UsuarioLogado.UsuarioId < 1)
Response.Redirect("~/Login");
² In current MVC applications, 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 in Session:
private void SessionAdd(Usuario dados)
{
System.Web.HttpContext.Current.Session.Add("UsuarioId", dados.UsuarioId);
}
I also use a Filter IAuthorizationFilter
which 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 do @Session["Nome"]
.
My applications have been working, however, I believe that the way I handle works well only for a few logged in users, but it is not the best way for many users.
Could you add some more information to help us? Something like what user data would you like to store? Name and ID? Are you using Identity? Could [Edit] and add how you are doing the authentication?
– Randrade
Do you already have something ready in Asp.NET MVC? Taking advantage, which version is using?
– Randrade
Yes, the applications where I work are already migrating to MVC, about 4 applications have already been fully migrated. As for the version, I’m using the 6.
– Thiago Araújo