Showing Detailed Error Messages - c#

I have a little Try Catch block that will tell the user more detailed information when invalid data is passed to my application:
try
{
//do something that throws an exception because of invalid data
}
catch (Exception ex)
{
throw new Exception("You have invalid data");
//throw ex;
}
When I run the application locally with invalid data it throws the Exception as expected:
You have invalid data
However when I publish it to the server it will only throw Exceptions like this for the same exact error:
There was an error processing the request.
I can still run the code with valid data, so I know everything else is working correctly.
Is there something else I have to add to my web.config?
Here's what I have now:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<httpErrors errorMode="Detailed" />
<asp scriptErrorSentToBrowser="true"/>
</system.webServer>

You shouldn't really be showing your site visitors exceptions in this way.
If you are validating user data, then do it with form validation at the user interface level.
Exceptions are for dealing with exceptional circumstances. If you have invalid data that hasn't come from your user but has caused some exceptional circumstances then your user probably doesn't need to know the details. It's common in this situation to show a page with some kind of generic "Technical Error" message that apologises for the problem and assures them someone is looking into it.
If you want to see the details of exceptions on your server during development then you should set custom errors to off in the web.config
<system.web>
<customErrors mode="Off">
</customErrors>
</system.web>

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.

Handling an 'A potentially dangerous Request.Form value was detected' exception without deactivating validation [duplicate]

This question already has answers here:
Handle "potentially dangerous Request.Form value..."
(3 answers)
Closed 9 years ago.
I am creating an ASP.NET application using C# for the scripting language. When I enter HTML code into the textboxes on my webpage I get the following exception 'A potentially dangerous Request.Form value was detected', as expected. I would like to be able to catch this exception so that I can put an error message out to the user, but I can only find articles on how to disable the validation; this is not something I'd like to do. Does anybody know where in the ASP.NET page lifecycle this exception would have to be handled, as I am having trouble catching it.
Thanks you.
to allow the html character you need to
change the attribute value of page directive
<%# Page ValidateRequest="false"
you can apply this as global level via web.config file inside
<system.web> section
<pages validateRequest="false" />
Note: But always avoid the last example because there is a huge security issue. The request validation feature in ASP.NET provides a certain level of default protection against cross-site scripting (XSS) attacks.
I don't know 100% if this would work, but I do something similar for other situations, so I think it will. But try adding an Application_error handler in the global.asax, and look for that exception type, if Server.GetLastError() returns that exception type, try redirecting to your error page. I don't know what the exception type is, but that is easy to find (or just check the message).
Something like:
void Application_Error(..)
{
var ex = Server.GetLastError();
if (ex != null && ex is <whateverexceptiontype>) { // or check ex.Message matches
HttpContext.Current.Response.Redirect("niceerrorpage.aspx")
}
}

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"]

Custom error page in web.config, will error info be lost?

If my web.config has:
<customErrors mode="Off" defaultRedirect="CustomErrorPage.aspx">
<error statusCode="401" redirect="~/CustomErrorPage.aspx?statusCode=401" />
<error statusCode="403" redirect="~/CustomErrorPage.aspx?statusCode=403" />
<error statusCode="404" redirect="~/CustomErrorPage.aspx?statusCode=404" />
...
</customErrors>
Now in my CustomErrorPage.aspx, how can I get the stacktrace information similar to how I see that yellow screen error page when there is no custom error page and it is outputted to the browser?
Or, because this is redirecting to the customerrorpage.aspx, is the error essentially lost at this point and I can't access the exception information?
This is a legacy application with complex virtual directories etc. so I can just drop one of those error libraries so easily at this point.
It's lost. You aren't even in the same request, since it's done by a redirect.
That last point is bad enough in itself (what's the point of redirecting someone to an error page?), but it affects you here. However, with redirectMode="ResponseRewrite" added to the customErrors element, then that solves this problem and also means that Server.GetLastError() will work.
Per this SO post (http://stackoverflow.com/questions/343014/asp-net-custom-error-page-server-getlasterror-is-null), if you are running .Net 3.5 SP1, you can use the redirectMode property on your customErrors element.
More info on the redirectMode:
http://msdn.microsoft.com/en-us/library/system.web.configuration.customerrorssection.redirectmode(v=vs.90).aspx
Once you do that, you'll have access to the error from Server.GetLastError():
http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.getlasterror.aspx
Edit: You'd be using the ResponseRewrite mode for redirectMode
In your global.asax you can catch the error and save it to be retrieved in the Error page.
You override Application_Error to catch the error.
The Exception is not lost. You can call Server.GetLastError() to get the last exception thrown.
Since it returns an Exception object, you can simply get call StackTrace to get the full stack trace.
You can log error in some file on server (you need to add Application_Error event handler in Global.asax.cs), or drop this row in webconfig to get yellow screen with exception.
Use GetLastError, that allows you (oddly enough) to get the last error that occurred.
http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.getlasterror.aspx

exception catching in Global.ascx app_error

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)

Categories