response write inside global asax - asp.net

this example dosent work for me ,I tried Response.write but I am getting nothing.
here is the sample
(is it also possiable come up a pop up window tell the error detail")
protected void Application_Error(object sender, EventArgs e)
{
// At this point we have information about the error
HttpContext ctx = HttpContext.Current;
Exception exception = ctx.Server.GetLastError ();
string errorInfo =
"<br>Offending URL: " + ctx.Request.Url.ToString () +
"<br>Source: " + exception.Source +
"<br>Message: " + exception.Message +
"<br>Stack trace: " + exception.StackTrace;
ctx.Response.Write (errorInfo);
ctx.Server.ClearError ();
}

Method signature of an event that is fired when an unhandled exception is encountered within the application in Global.asax is:
void Application_Error(object sender, EventArgs e)
{
// your code...
}

Related

How can I tell if Request/Response is available in Application_Error?

If Application_Error is triggered by an exception in the application start up i.e. RouteConfigor BundleConfig how can you check if the Request/Response is available? Currently the call to Response.Clear throws System.Web.HttpException with additional information Response is not available in this context.
void Application_Error(object sender, EventArgs e)
{
//Log error
Log.Error(e);
//Clear
Response.Clear();
Server.ClearError();
//Redirect
Response.Redirect("~/Error");
}
Other questions suggest rewriting to not use Response or to use HttpContext.Current.Response or changing IIS config.
In summary; how can I tell if the error has occurred during app start?
You want to check whether it is HttpException.
protected void Application_Error(Object sender, EventArgs e)
{
var exception = Server.GetLastError();
// Log error
LogException(exception);
var httpException = exception as HttpException;
if (httpException != null)
{
Response.Clear();
Server.ClearError();
Response.TrySkipIisCustomErrors = true;
Response.Redirect("~/Error");
}
}

The object reference error in asp.net

i am using the following code on page_load event in asp.net
protected void Page_Load(object sender, EventArgs e)
{
lblDate.Text = System.DateTime.Now.ToLongDateString();
if(!IsPostBack)
{
setImageUrl();
}
}
protected void Timer1_Tick(object sender, EventArgs e)
{
setImageUrl();
}
private void setImageUrl()
{
Random rnd = new Random();
int i = rnd.Next(1, 7);
Image1.ImageUrl ="~/SlideImages/"+ i.ToString() + ".gif";
}
code is working well at page-load event but when i click any other menu item it gives me the following error message
Object reference not set to an instance of an object.
Well I am 95% sure that i is null because when you ToString() and object if it is null it will throw a fatal exception. What I would do is set a break point on the line throwing the error and run this project in debug mode and see what I is returning. If it is null then there is your problem. So you would have to find out why your Random Method isn't instantiating properly.
Also a recommendation would be to do a String.Format on that line as well
Image1.ImageUrl = String.Format("~/SlideImages/{0}.gif", i);
This will give you the same result set as long as i is valid and String.Format will format null as an empty string. So you will have a graceful fail and your image just won't show up which means you know your problem.

implementation of customized application_end method in asp.net

I want to have a method which gets executed when session expires or user logs out or user closes the web application. How can i catch these events in asp.net and execute a method ?
I'm building a web app in vs 2008/asp.net/c#.
Please help me.
Thanks in anticipation
use Global.asax file
Refer the link to use Global.asax file http://www.dotnetcurry.com/ShowArticle.aspx?ID=126
Right click on The solution and the Add new item the Add Global.asax in the solution Then after
which have the following Event
<script runat="server">
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
//Utils.LoadExtensions();
}
void Application_End(object sender, EventArgs e)
{
ClsCollege ObjClsColledge = new ClsCollege();
ObjClsColledge.TruncateAllUserDetails(Session["UserSessionId"].ToString());
ObjClsColledge.TruncateAllUserDetailsPrefrance(Session["UserSessionId"].ToString());
}
void Application_Error(object sender, EventArgs e)
{
HttpContext context = ((HttpApplication)sender).Context;
Exception ex = context.Server.GetLastError();
if (ex == null || !(ex is HttpException) || (ex as HttpException).GetHttpCode() == 404)
{
return;
}
StringBuilder sb = new StringBuilder();
try
{
sb.AppendLine("Url : " + context.Request.Url);
sb.AppendLine("Raw Url : " + context.Request.RawUrl);
while (ex != null)
{
sb.AppendLine("Message : " + ex.Message);
sb.AppendLine("Source : " + ex.Source);
sb.AppendLine("StackTrace : " + ex.StackTrace);
sb.AppendLine("TargetSite : " + ex.TargetSite);
ex = ex.InnerException;
}
}
catch (Exception ex2)
{
sb.AppendLine("Error logging error : " + ex2.Message);
}
if (BlogSettings.Instance.EnableErrorLogging)
{
Utils.Log(sb.ToString());
}
context.Items["LastErrorDetails"] = sb.ToString();
context.Response.StatusCode = 500;
//// Custom errors section defined in the Web.config, will rewrite (not redirect)
//// this 500 error request to error.aspx.
}
void Session_Start(object sender, EventArgs e)
{
}
void Session_End(object sender, EventArgs e)
{
ClsCollege ObjClsColledge = new ClsCollege();
ObjClsColledge.TruncateAllUserDetails(Session["UserSessionId"].ToString());
ObjClsColledge.TruncateAllUserDetailsPrefrance(Session["UserSessionId"].ToString());
}
</script>
The Event Session_start(),Session_End() and Application_End() you will able to track the
Event.

ASP.Net Response.Redirect not working in Application_Error?

I don't know why the Response.Redirect not working properly when I deploy my code to IIS7? The white/yellow error page always get displayed instead of my Errors.aspx. But when debug running using Visual Studio on my computer, it runs just fine?
protected void Application_Error(object sender, EventArgs e)
{
ILog log = LogManager.GetLogger(typeof(Global).Name);
Exception objErr = Server.GetLastError().GetBaseException();
log.Error(objErr);
string err = "Error Caught in Application_Error event\n" +
"\nError Message:" + objErr.Message.ToString() +
"\nStack Trace:" + objErr.StackTrace.ToString();
EventLog.WriteEntry("Kiosk", err, EventLogEntryType.Error);
Server.ClearError();
Response.Redirect("~/Error.aspx", false);
}
I had the same problem and solved it with:
HttpContext.Current.ClearError();
Response.Redirect("~/Error.aspx", false);
return;
HttpContext.Current.Server.ClearError();
HttpContext.Current.ClearError();
====================================================================
Redirect to NEW VIRTUAL! directory (Error)
HttpContext.Current.Response.Redirect([http://localhost:8990/Error/ErrorPageServer.aspx]);
For me the below code worked.
HttpContext.Current.Server.ClearError();
HttpContext.Current.Response.Redirect("~/ErrorPage.aspx");
protected void Application_Error(object sender, EventArgs e)
{
Exception objErr = Server.GetLastError().InnerException;
//Logging.WriteToErrorLog("Error Caught in Application_Error event", objErr);
HttpContext.Current.Server.ClearError();
HttpContext.Current.Application.Add("test", objErr);
HttpContext.Current.Response.Redirect("~/Home/Index");
return;
}
Try to turn off the CustomError in web.config. It will give you more specific about the error details. Maybe it doesn't the error from Response.Redirect.

Problem in Application_Error in Global.asax

my problem is User.Identity.Name or Request.Url.AbsoluteUri in exception handling is empty when exception email to me.
this is Application_Code:
void Application_Error(object sender, EventArgs e)
{
Server.Transfer("~/errors/default.aspx");
}
and this is default.aspx code:
protected void Page_Load(object sender, EventArgs e)
{
if (Server.GetLastError() == null)
return;
Exception ex = Server.GetLastError().GetBaseException();
if (ex == null)
return;
string message = string.Format("User: ", User.Identity.Name);
message += Environment.NewLine;
message += string.Format("AbsoluteUri: ", Request.Url.AbsoluteUri);
message += Environment.NewLine;
message += string.Format("Form: ", Request.Form.ToString());
message += Environment.NewLine;
message += string.Format("QueryString: ", Request.QueryString.ToString());
message += Environment.NewLine;
but i receive email like this (this is header without full exception content):
User:
AbsoluteUri:
Form:
QueryString:
Browser Capabilities:
Type = IE8
Name = IE
Version = 8.0
Platform = WinXP
Is Crawler = False
Supports Cookies = True
Supports JavaScript = 1.2
why username and request url is emty?
this problem is exist when i replace transfer with redirect or i don't use both.
tanx
You do not have set the string.Format in the correct way
Try this.
string.Format("AbsoluteUri: {0}", Request.Url.AbsoluteUri);
How ever I suggest to use StringBuilder for this code.

Resources