Use session variables in to Hangfire Recurring Job


#1

Hi,

I have integrated hangfire in to Asp.net web application and trying to use session variables in to Hangfire Recurring Job as like below :

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        HangfireSyncServices objSync = new HangfireSyncServices();

        var options = new DashboardOptions
        {
            Authorization = new[] { new CustomAuthorizationFilter() }
        };
        app.UseHangfireDashboard("/hangfire", options);
        
        app.UseHangfireServer();

        //Recurring Job
        RecurringJob.AddOrUpdate("ADDRESS_SYNC", () => objSync.ADDRESS_SYNC(), Cron.MinuteInterval(30));
        
    }
}

My “HangfireSyncServices” class as below:

public partial class HangfireSyncServices : APIPageClass
{
	public void ADDRESS_SYNC()
	{
		string userName = Convert.ToString(Session[Constants.Sessions.LoggedInUser]).ToUpper();
                //Exception throwing on above statement..
		//........Rest code.......
	}
}

public abstract class APIPageClass : System.Web.UI.Page
{
	//common property & methods...
}

but I am getting run time exception as below at the time of getting value in to “userName”:
Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the <system.web><httpModules>
section in the application configuration.

I have tried to resolve above error using this LINK & other solution also but not able to resolved yet. can anyone help me on this issue.

Thanks in advance,
Hiren


#2

The job doesn’t know anything about sessions, because it is not bound to any HttpContext.


#3

@pieceofsummer, Thanks for reply, is there any work around to bound HttpContext to use session any how?


#4

You can’t and shouldn’t do that!

There’s no way to determine which HttpContext should be bound since the job is executed outside of HTTP requests pipeline. There could be multiple ongoing requests the moment it is executed, or no requests at all. The job may be even executed by a different process/computer than your web server.


#5

@pieceofsummer Ok thanks got it.