Quite difficult, yes, fortunately, this is resolved.
You need to implement Application_PreRequestHandlerExecute in Global.asax
here is the code
/// <summary> /// The event occurs just after Initialization of Session, and before Page_Init event /// </summary> protected void Application_PreRequestHandlerExecute(Object sender, EventArgs e) { // here it checks if session is reuired, as // .aspx requires session, and session should be available there // .jpg, or .css doesn't require session so session will be null // as .jpg, or .css are also http request in any case // even if you implemented URL Rewritter, or custom IHttp Module if (Context.Handler is IRequiresSessionState || Context.Handler is IReadOnlySessionState) { // here is your actual code // check if session is new one // or any of your logic if (Session.IsNewSession || Session.Count < 1) { // for instance your login page is default.aspx // it should not be redirected if, // if the request is for login page (ie default.aspx) if (!Context.Request.Url.AbsoluteUri.ToLower().Contains("/default.aspx")) { // redirect to your login page Context.Response.Redirect("~/default.aspx"); } } } }
Edit 1: Explanation and conclusion
As one of the guys said, the ASP.NET application life cycle .
There are many events that occur.
In fact, events in Global.asax occur in the following sequence
Conclusion: All events prior to AcquireRequestState do not have a Session object, because Session is not loaded by ASP.Net, so any event from the * "AcquireRequestState * * event provides a Session object, so this problem is solved. However, some checks are required, as I mentioned in the code above
Waqas raja
source share