How to keep alive a variable among a class inherit from ApiController and other one inherit from ExceptionFilterAttribute

135 Views Asked by At

I have my controller SomeController and its inherited from ApiController, also, I have an ActionFilter:

FilterConfig

public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            //filters.Add(new HandleErrorAttribute());
            GlobalConfiguration.Configuration.Filters.Add(new LogExceptionFilterAttribute());
        }
    }

ErrorLogService

public static class ErrorLogService
    {
        public static void LogError(Exception ex, string metodo, string clase)
        {
            Utilidades.EnviarErrorHTTP(ex, null, metodo, clase);
        }
    }

LogExceptionFilterAttribute

public class LogExceptionFilterAttribute : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext context)
        {            
            //TODO
        }
    }

Well, the session is handled by the ApiController and in my SomeController I can use it like:

var session = TokenUser;

But, there nothing in my ErrorLogService to invoke the function to know the token.

Is there a way to share this variable if it is different in each session? (TokenUser is an object).

1

There are 1 best solutions below

0
Benjamin RD On BEST ANSWER

I found a way to do it.

In the Global.asax you must add the next code:

protected void Application_PostAuthorizeRequest()
        {
            System.Web.HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
        }

And now, you are available to use Session:

var session = System.Web.HttpContext.Current.Session;
session["token"] = sesion;

And the variable session would persist in the application.