Why access to a Session within an Actionfilter is behaving this way

Asked

Viewed 33 times

1

Greeting to all.

I am developing an application in Asp.NET MVC5 and found a following problem:

The application needs me to log in from any screen it accesses via browser. To decrease the amount of code lines in my views I created a Actionfilter which will serve both to validate the login and to popular the Sessions that I need to keep on my site for proper functioning of the requester.

Following this logic, when making the first access to the site the sessions are filled in the correct way, until then no problem, however when we updated for example the user profile to ensure more access to it we realized that the sessions were not being updated automatically between the navigation of the screens (Actionfilter is configured to run before the execution of the actions). Realizing this, I thought of a workaround, creating a button that would call an action to update these sessions and everything ok, right? Wrong!

When I use for example:

public ActionResult AtualizaPerfil()
{
...
HttpContext.Session["PerfilUsuario"] = idPerfil;
...
}

within my action I assign a value to the session and at the end of the action I redirect to a view return RedirectToAction("Index", "Home"); that has Actionfilter bound [ControleAcessoActionFilter].

Within Actionfilter, I have the Method to follow:

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
...
if (HttpContext.Current.Session["PerfilUsuario"] == null)
   {
       filterContext.HttpContext.Session.Add("PerfilUsuario", idPerfil);
   }
...
}

Lo that we arrived at the problem, the Session["Profile"] of my view did not assign the value to my Httpcontext.Current.Session["Profile"], I found it very strange since both have equal origin following the logic of this post here from Stackoverflow International.

Would anyone have any other explanation for this case?

  • Aren’t you working in different contexts? if (HttpContext.Current.Session["PerfilUsuario"] == null) and filterContext.HttpContext.Session?

  • I don’t think @Leandroangelo, since httpContext is theoretically inherited by filterContext since it receives all the parameterization of the action before it is executed.

1 answer

1


Good morning Personal!

I found the solution at the end of Friday. From what I understand about this issue of sessions and actionFilters, if the creation of the Session is made within the actionFilter, I can’t execute Abandon(), Clear() or RemoveAll() for sessions in some view action, the Session that will be validated in actionFilter will be in a different context/instance of the action for the sessions (it seems bizarre, but this happened even in my VS2017).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.