exception catching in Global.ascx app_error - c#

I have web application in asp.net and C#
I am trying to handle exceptions if they occur anywhere within this application.
like suppose the behaviour should be if and exception like this occurs
//generate your fictional exception
int x = 1;
int y = 0;
int z = x / y;
it should catch it in the app_error of the global.ascx file and redirect it to the Default.aspx page. i got the logging part but the redirect is not working as i still get the
Server Error in '/' Application.
page. or may be it is redirecting and getting killed in the middle..
this is what is there in global.ascx
protected void Application_Error(object sender, EventArgs e)
{
logger.Fatal(this.Server.GetLastError().GetBaseException());
logger.Info("FatalLogger Passed");
//get reference to the source of the exception chain
Exception ex = Server.GetLastError().GetBaseException();
Response.Redirect("~/Default.aspx?error=MessageHere");
}
this in the code in web.config
<authentication mode="Forms">
<forms loginUrl="Login.aspx" defaultUrl="~/Default.aspx" name="GUI" slidingExpiration="true" timeout="30" path="/">
</forms>
</authentication>
any ideas.. ill; be happy to provide more information.
Thanks
ok i want this approach for a reason because whenever there is an error the user get logged out and i dont want that to happen instead go to the default page

Have you tried calling Server.ClearError() before the redirect in Application_Error? It's been a while since I played with this, but I believe that if you don't call ClearError then the framework still thinks the error is unhandled.

Configure custom error pages
BTW, I recommend ELMAH for the logging part...

Try using Server.Transfer(page)
Also be wary of passing the error message via the Query String as it can open you up to XSS problems. Pass an error code and then display the message dependent on the code (using a switch statement)

Related

.NET Retrieving Error StackTrace in Custom Error Page

I am running .NET 3.5 and IIS7.
I was trying to use customErrors to redirect to a custom error page that could still display the exception details, stack trace, etc. I had a hard time getting it to work, trying about 20 different approaches I found online (mostly on stackoverflow), some of which were slight variations of others. I preferred to have the redirect to happen in Web.config because I wanted the custom error page to be easily found/edited outside the code.
Here's what I finally got to work. I'm posting because I tried so many of the more complex approaches I found here and they didn't work for me, and just wanted to post the simple one that ultimately did.
Web.config:
<customErrors mode="RemoteOnly" defaultRedirect="~/Error.aspx" redirectMode="ResponseRewrite" />
Without the redirectMode="ResponseRewrite", I could not access the exception details from my custom error page.
Error.aspx
protected void Page_Load(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
if (ex != null)
{
if (ex.GetBaseException() != null) ex = ex.GetBaseException();
litErrorMessage.Text = String.Format("<div class=\"error\">{0}</div>", ex.Message);
litErrorStackTrace.Text = String.Format("<b>Source:</b>\n{0}\n<b>Stack Trace:</b>\n{1}\n", ex.Source, ex.StackTrace);
}
else
{
litErrorStackTrace.Text = "No Exception information available.";
}
}
I also tried using
HttpException ex = (HttpException)HttpContext.Current.Server.GetLastError();, as seen in some examples, but that did not work.
I also tried all kinds of code in Global.asax -> Application_Error, but it turns out it was not necessary. After trying all kinds of code there, including storing session variables, Application_Error is now empty.

ASP.NET Custom Error Page for Web App that uses a Master Page

Reference KB306355: How to create custom error reporting pages in ASP.NET by using Visual C# .NET
I understand how to create a Custom Errors page. There are many examples of how to do it, like in the link above.
None of the examples I have found shows how to do what I am after.
I have a Web Application that uses a Master Page.
In my Master Page, I have a Label control used for errors that all pages will see:
<h4 id="bannerError"><asp:Label ID="lblError" runat="server" /></h4>
In the code behind on that Master Page, I have this:
public void Page_Error(object sender, EventArgs e) {
var err = Server.GetLastError().GetBaseException();
ErrorMessage = String.Format("URL {0}: {1} Error: {2}", Request.Url, err.GetType(), err.Message);
Server.ClearError();
}
public string ErrorMessage {
get { return lblError.Text; }
set {
LogError(value);
lblError.Text = value;
}
}
The ErrorMessage is a property. My other pages can easily access it, and I was easily able to edit out the part about writing the error to our server's database.
The Web.config page configuration (snippet):
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
<customErrors defaultRedirect="Default.aspx" mode="On">
<error statusCode="403" redirect="Default.aspx" />
<error statusCode="404" redirect="Default.aspx" />
</customErrors>
</system.web>
</configuration>
How would I edit my files so that any errors that occur on any of my pages in my application (that derive from Master Page), simply show this basic information through the Master Page instead of redirecting the page to another URL?
I know the question was about how to get the MasterPage solution to work, but I think that using the application level Error event is the best way to make a catch-all error handler to forward to an error page.
You basclly need to handle the Application_Error in the Global.asax file. Here you can not only handle all page-level errors, but also application-level errors and HTTP errors of some types (if they can reach your application pipeline).
I think this is a better and more cetralized method. Adding MasterPage-level or BasePage-level error event handlers is also possible, but as a second layer.
Look here for a good example of doing this.
You won't be able to use controls to set the error message for unhandled Page level errors because no controls will be created (see this MS article). You could catch errors on the Page level and set the Master Page content like this:
protected override void OnError(EventArgs e) {
var err = Server.GetLastError().GetBaseException();
var errorMessage = String.Format("URL {0}: {1} Error: {2}", Request.Url, err.GetType(), err.Message);
((MyMasterPageClass)Master).ShowError(errorMessage);
Server.ClearError();
}
And then in the Master Page set the content directly:
public void ShowError(string message) {
Response.Write(string.Format("<h4 id=\"bannerError\">{0}</h4>", message));
}
But again, your Master Page wouldn't be rendering anyway, so it sort of defeats the purpose. If you really want to avoid the redirecting to an error page, you could load the content with ajax using something like jQuery.get(), and then display the results/errors as needed:
var request = $.get("www.mywebsite.com/Bugs2012.aspx");
request.done(function (data) {
$("#childContent").html(data);
});
request.fail(function (xhr, status, msg) {
var displayMsg = "Request could not be completed. ";
if (status === "error") {
switch (xhr.status) {
case 404:
displayMsg += "The content could not be found.";
break;
}
}
$("#bannerError").text(displayMsg);
});
I tried to create a jsfiddle, but it's a bit contrived because of the cross-domain ajax issues: js fiddle

ASP.NET HeadLoginView Logout Click. Logs out of other local websites too

I have 2-3 web projects ( beginner ones). In all the websites I have a login control where a user can log in. When the user logins with correct info, I set the
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
if (CHUser.AunthencateLogin(Login1.UserName, Login1.Password))//Checks with database
e.Authenticated = true;
else
e.Authenticated = false;
}
Up to here is fine, but the problem occurs when I login into 2 separate websites (local) at same time, and log out at any one of them. When I log out at one the other website is also logged out ( when refreshed). Following is the code I use when logging out.
protected void LoginStatus1_LoggingOut(object sender, LoginCancelEventArgs e)
{
Session.Clear(); //though logout works without this code. It is for other
//sessions that are manually created by me
}
I can't see to find out what's the cause of it. I am also new to web development.
I would also like to know if this is the right way of logging in a user.
(Answered in a question edit. converted to a community wiki answer. See What is the appropriate action when the answer to a question is added to the question itself? )
The OP wrote:
Thanks #Aristos. the problem was solved by using the following code on web.config 1st project
<authentication mode="Forms">
<forms name=".Cookie1" ... />
</authentication>
2nd project
<authentication mode="Forms">
<forms name=".Cookie2" ... />
</authentication>

How to 'retrieve' browser-typed 404 url and make it auto redirect on c#

I have a c# web application on i.e. http://mysite.com
User opens his browser and types http://mysite.com/anywrongpath
Which I want to do is to get the "exact" url ( /anywrongpath ) and THEN redirect that user to i.e. /MainPage.aspx
I think I can handle redirection with:
protected void Application_Error(object sender, EventArgs e)
{
HttpException httpException = Server.GetLastError() as HttpException;
if (httpException.ErrorCode == 404)
Response.Redirect("/MainPage.aspx");
}
However, I have no idea how to handle the retrieve process of typed url. I made a research of "Sessions" , "Request.ServerVariables" , "Request.Url" etc but I couldnt solve the problem.
I am open for any idea how to solve it, and really glad if you give tiny code samples, thanx
Murat
Edit your web.config file and put something like this in the system.web section
<customErrors mode="RemoteOnly" defaultRedirect="Error.aspx">
<error statusCode="404" redirect="MainPage.aspx" />
</customErrors>
When your user types an address like mysite.com/non-existant, IIS redirects him to mysite.com/MainPage.aspx?aspxerrorpath=/non-existant
This way, you can get the Request.QueryString["aspxerrorpath"]

ASP.NET login form authentication without login control

I am using ASP.NET membership and on registration page trying to login without a login control.
When user clicks on the register button, the control goes to redirect.aspx page.
But in that page, while I am trying to redirect to the members homepage its throwing the following error.
ERROR -
Unable to evaluate expression because the code is optimized or a native frame
is on top of the call stack.
Web.config -
<authentication mode="Forms">
<forms name=".SSOAuth" loginUrl="login.aspx" defaultUrl="Redirect.aspx"
protection="Validation" timeout="30000"/>
</authentication>
RegistrationPage code -
protected void btnRegister_Click(object sender, EventArgs e)
{
MembershipUser userMemb = Membership.CreateUser(
txtemail.Text.Replace("'", "''").ToString(),
txtPassword.Text.Replace("'", "''").ToString(),
txtemail.Text.ToString());
Roles.AddUserToRole(txtemail.Text.ToString(), "Member");
FormsAuthentication.RedirectFromLoginPage(txtemail.Text.Trim(), false);
}
Redirect.aspx.cs code -
try
{
if (User.IsInRole("Member"))
{
string UserName = User.Identity.Name;
Response.Redirect("~/Member/MembeHome.aspx");
}
}
catch(Exception ex) {}
Read this document (issue and solution) ThreadAbortException Occurs If You Use Response.End, Response.Redirect, or Server.Transfer
Use Response.Redirect(url,false)
Response.Redirect("~/Member/MembeHome.aspx",false);

Categories