I have a login page that works only with Firefox. It does not work with any other browsers.
When I checked the event log, I saw a "response is not available in the current context". It tells me that the error is in the global.asax file, at the response.redirect line:
void Session_End(object sender, EventArgs e)
{
Response.Redirect("~/Login.aspx?li=1");
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.
}
What could be the problem?
I have tried httpcontext.Current as suggested but then I get a Null Reference Exception, Object Reference not set to an instance of an object
Thank you.
Try using HttpContext.Current.Response it should definitely work.
Did you try using HttpContext.Current.Response?
Happy coding!!
Related
I wanna free some DB resources and set few flags when User Session Ends in ASP.NET Site. But when I write my code to access session variables in Session End method of Global.asax file, its getting called everytime the App starts, Why this weird behavior?
Secondly, I want to access user specific session variables and free them up in DB on Session End. Thus I am using few session Variables where I am setting them in a webmethod on a Page and trying to access them on Session End. But since Session end is being called on App start up its always throws Null reference exception.
Here is mycode. for Setting up a variable in Webmethod in a .aspx page
[WebMethod(EnableSession=true)]
protected void checkUser()
{
Session["TestObject"] = "Hello I am session";
}
In my global.asax file I am trying to access as follows in Session_End method
void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.
if (this.Context.Session != null && this.Context != null)
{
string k = this.Session["TestObject"].ToString();
}
}
I even tried HttpContext.current.Session etc.. but none worked. All are throwing exception as Session end is called on App start up and even when session timed out.
I have an asp.net application and I am trying to handle custom exception using Application_Error. It works nicely but I have new requirement to set the error data in Session object(or any object that can maintain state) and redirect to Error.aspx page. THere I am just removing the error messages after reading them.
So, Whatever I add to session object(or if I change a previously existing value) in Application_error and when I call Redirect. In the error.aspx I don't see any of the value as if Session was in readonly mode in Application_error.
I tried by calling
session.IsReadOnly
to see if its read only. But it returns false!!
I've just come across this problem myself and, after a couple of hours of messing around, managed to solve it. The issue is that Application_Error() clears the session after executing as part of some sort of "cleanup" routine which you need to stop.
The solution I found is as follows:
Call Server.ClearError(); - this clears the last error from the application and stops the "cleanup" taking place, thus preserving session.
The (unwanted imho) side-effect of this is that it no longer performs the automatic redirect to the error page, so you need to explicitly call Response.Redirect("~/error.aspx");
So, something like this:
protected void Application_Error(object sender, EventArgs e)
{
// Grab the last exception
Exception ex = Server.GetLastError();
// put it in session
Session["Last_Exception"] = ex;
// clear the last error to stop .net clearing session
Server.ClearError();
// The above stops the auto-redirect - so do a redirect!
Response.Redirect("~/error.aspx");
}
If you don't want to hard-code the URL, you could grab the defaultRedirect URL directly from the customerrors section in the web.config, which would give you something like this:
protected void Application_Error(object sender, EventArgs e)
{
// Grab the last exception
Exception ex = Server.GetLastError();
// put it in session
Session["Last_Exception"] = ex;
// clear the last error to stop .net clearing session
Server.ClearError();
// The above stops the auto-redirect - so do a redirect using the default redirect from the customErrors section of the web.config!
var customerrors = (CustomErrorsSection)WebConfigurationManager.OpenWebConfiguration("/").GetSection("system.web/customErrors");
Response.Redirect(customerrors.DefaultRedirect);
}
You could use the Cache and an appropriate naming strategy for your key, like this:
protected void Application_Error(object sender, EventArgs e)
{
HttpContext.Current.Cache["error:" + Session.SessionID] = Server.GetLastError();
Response.Redirect("Error.aspx");
}
in the Error.aspx page you ca read it like this:
var error = Cache["error:" + Session.SessionID];
Check this, the problem is with the redirect call.
Don't redirect after setting a Session variable (or do it right)
Add a directive to the Global.asax file, Imports the System.Web Namespace
<%# Import Namespace="System.Web" %>
void Application_Error(object sender, EventArgs e) {
string message = Server.GetLastError().Message;
Session["error"] = message;
Server.Transfer("Error.aspx");
}
Write the error message added in the sesion object in the Error.aspx page
protected void Page_Load(object sender, EventArgs e){
if (!this.IsPostBack)
Response.Write(Session["error"].ToString());
}
The problem might that the AcquireRequestState event might not have fired when the exception was raised in your application, you will be able to set a session value only after this particular event is fired as this is the stage where the application state is set
I have an asp.net application and I am trying to handle custom exception using Application_Error. It works nicely but I have new requirement to set the error data in Session object(or any object that can maintain state) and redirect to Error.aspx page. THere I am just removing the error messages after reading them.
So, Whatever I add to session object(or if I change a previously existing value) in Application_error and when I call Redirect. In the error.aspx I don't see any of the value as if Session was in readonly mode in Application_error.
I tried by calling
session.IsReadOnly
to see if its read only. But it returns false!!
I've just come across this problem myself and, after a couple of hours of messing around, managed to solve it. The issue is that Application_Error() clears the session after executing as part of some sort of "cleanup" routine which you need to stop.
The solution I found is as follows:
Call Server.ClearError(); - this clears the last error from the application and stops the "cleanup" taking place, thus preserving session.
The (unwanted imho) side-effect of this is that it no longer performs the automatic redirect to the error page, so you need to explicitly call Response.Redirect("~/error.aspx");
So, something like this:
protected void Application_Error(object sender, EventArgs e)
{
// Grab the last exception
Exception ex = Server.GetLastError();
// put it in session
Session["Last_Exception"] = ex;
// clear the last error to stop .net clearing session
Server.ClearError();
// The above stops the auto-redirect - so do a redirect!
Response.Redirect("~/error.aspx");
}
If you don't want to hard-code the URL, you could grab the defaultRedirect URL directly from the customerrors section in the web.config, which would give you something like this:
protected void Application_Error(object sender, EventArgs e)
{
// Grab the last exception
Exception ex = Server.GetLastError();
// put it in session
Session["Last_Exception"] = ex;
// clear the last error to stop .net clearing session
Server.ClearError();
// The above stops the auto-redirect - so do a redirect using the default redirect from the customErrors section of the web.config!
var customerrors = (CustomErrorsSection)WebConfigurationManager.OpenWebConfiguration("/").GetSection("system.web/customErrors");
Response.Redirect(customerrors.DefaultRedirect);
}
You could use the Cache and an appropriate naming strategy for your key, like this:
protected void Application_Error(object sender, EventArgs e)
{
HttpContext.Current.Cache["error:" + Session.SessionID] = Server.GetLastError();
Response.Redirect("Error.aspx");
}
in the Error.aspx page you ca read it like this:
var error = Cache["error:" + Session.SessionID];
Check this, the problem is with the redirect call.
Don't redirect after setting a Session variable (or do it right)
Add a directive to the Global.asax file, Imports the System.Web Namespace
<%# Import Namespace="System.Web" %>
void Application_Error(object sender, EventArgs e) {
string message = Server.GetLastError().Message;
Session["error"] = message;
Server.Transfer("Error.aspx");
}
Write the error message added in the sesion object in the Error.aspx page
protected void Page_Load(object sender, EventArgs e){
if (!this.IsPostBack)
Response.Write(Session["error"].ToString());
}
The problem might that the AcquireRequestState event might not have fired when the exception was raised in your application, you will be able to set a session value only after this particular event is fired as this is the stage where the application state is set
This problem seems related to this post, but I was not able to infer a solution from the thread.
I noticed this code in an application I inherited (after noting in a log file that an exception was being eaten):
protected void Session_End(object sender, EventArgs e)
{
try
{
FormsAuthentication.SignOut();
FormsAuthentication.RedirectToLoginPage();
//if (this.Context.Handler is IRequiresSessionState || this.Context.Handler is IReadOnlySessionState)
//{
// FormsAuthentication.SignOut();
// FormsAuthentication.RedirectToLoginPage();
//}
}
catch (Exception ex)
{
this.GetType().GetLogger().Error(ex);
}
}
I am wondering a few things. First, how is SignOut throwing a null reference exception? Is it an exceptional case, or am I doing something inherently wrong in my program? Next, what should I be testing against to head-off this exception before it is thrown?
15:51:57,288 [13] ERROR ASP.global_asax - System.NullReferenceException: Object reference not set to an instance of an object.
at System.Web.Security.FormsAuthentication.SignOut()
at MvcApplication.Session_End
Thanks
It's important to realize that Session_End doesn't get necessarily executed in the the context of an HTTP request. It may run when a session times out. You cannot send anything to the client at that time, because it simply isn't there anymore!
Consequently, you should not try to delete the forms authentication cookie in Session_End. If you want, you should do that sooner, when a "Sign Off" button is clicked somewhere in your application. If you need a user's forms authentication ticket to expire after a timeout occures, you should simply set the cookie expiration time appropriately (possibly equivalent to session timeout value) in the config file.
As stated in the title my web application builds successfully, although every time I run it in debug mode I get the following .Net error:
If I hit refresh then the application gets no more errors until I next start it up again, any ideas?
Here is my global.asax file:
<%# Application Language="C#" Inherits="MyCompany.Web.MyApp.Shell.CustomWebClientApplication" %>
<script runat="server">
void Session_End(Object Sender, EventArgs e)
{
FormsAuthentication.SignOut();
}
protected void Session_Start(Object sender, EventArgs e)
{
if (Session.IsNewSession)
{
Response.Redirect(System.Web.Configuration.WebConfigurationManager.AppSettings["HomePage"]);
}
}
protected void Application_Error(Object sender, EventArgs e)
{
System.Exception oops = Server.GetLastError();
//Injection attack error handling
if (oops.GetBaseException() is System.Web.HttpRequestValidationException)
{
Response.Redirect("ErrorPage.aspx");
}
}
</script>
You have something which is trying to access a variable which is set to null (or hasn't been initialized). Do you have anything in the Global.asax or anything that fires on the start of the application? Do you have any asynchronous operations that fire on the start of the application?
Check on your Home.aspx page to see what is happening there. It looks like your application redirects to that page, so I would guess that on either the init or page_load event there is something which is executing that it causing the problem.
System.Exception oops
I think that this is source of problems. When there is no object returned from
Server.GetLastError();
then you will get NullReferenceException on line
oops.GetBaseException()
It makes perfect sense. On first run, oops is null (because no error occured before), thus throwing NullReferenceException. On second page refresh, GetLastError() returns object reffering previous errror (NullReferenceException) and page is displayed. Always check objects for null before accessing them.
Anyway, you can always try catching all runtime exceptions (Debug->Exceptions->Common Language runtime) and see where a problem is.
Sounds like an initialization issue. You're probably trying to use a resource before it's initialized, but by the time you refresh it's had time to be initialized.