Throwing Exception with inner SecurityException only displays inner exception in ASP.NET MVC - asp.net

If I add the following line to an ASP.NET MVC action method
throw new Exception("outer", new SecurityException("inner"));
the error that is actually displayed on the yellow screen of death is the inner SecurityException with absolutely no mention of the outer exception.
SecurityException
Description: The application attempted to perform an operation not
allowed by the security policy. To grant this application the
required permission please contact your system administrator or change
the application's trust level in the configuration file.
Exception Details: System.Security.SecurityException: inner
Source Error:
An unhandled exception was generated during the execution of the
current web request. Information regarding the origin and location of
the exception can be identified using the exception stack trace below.
Stack Trace:
[SecurityException: inner]
Is this expected behavior?
It doesn't seem to matter what type the outer exception is. Even if it is another SecurityException, the message is never displayed. The default SecurityException error message is so vague that I want to catch it and add some more specific information. This works fine if I do not include the original SecurityException as the innerException but ideally I would like to do this.

This behaviour originates in the ASP.NET "core", not in ASP.NET MVC. Unfortunately, the error formatter classes are internal, and the consuming types do not provide any extension points that would allow one to tweak the behaviour without replacing the error reporting mechanism. The workaround is to replace the default "yellow screen of death" page by a custom error page/view in which one exposes the information that one prefers.
This is exactly what one should usually be doing for production. In your case, it just means that you would have an alternate version for debug instead of using the ASP.NET-provided default.

in general you should never throw Exception class/object directly but only derived ones, for example:
throw new SecurityException("user should not be allowed to access this method...");
in a situation like this what are you missing in the log or in the page?
if you use an application global exception handler and you log from there with either Log4Net or NLog you should be able to access all exception chain from outer to inner and so on depending on how you configure and use the logging framework. The Yellow page of IIS / ASP.NET might not be complete but should show the stack trace anyway.
if you want to throw your own exception from a catch block you wrap the actual exception coming from the catch in this way:
throw new SecurityException("user should not be allowed...", exc);
Edit: tried what you suggested and got the following logged in a text file by Log4Net:
System.Security.SecurityException: more explicit exception --->
System.Security.SecurityException: original exception at
EDICheckerApp.Program.boom() in
C:\DEV_RPP\Program.cs:line 45
--- End of inner exception stack trace --- at EDICheckerApp.Program.boom() in
C:\DEV_RPP\Program.cs:line 49
at EDICheckerApp.Program.Main(String[] args) in
C:\DEV_RPP\Program.cs:line 27

Related

Handling Fatal Errors with the Twig Exception Controller

I am working on a Symfony project and I am trying to create user-friendly error pages for the production environment. To do this, I have overridden the twig.exception_controller parameter. That process is described in the Symfony Documentation. In overriding the exception controller, I have been able to create custom error pages for instances were no routes exist, or an uncaught exception in thrown. I have not been able to get this to work with fatal errors, and that is what my question is about.
Is it possible to catch/handle fatal errors in Symfony? I am not attempting to continue running the application (as the answerer of this question suggests) when a fatal error occurs. I would simply like to show an error page, aside from the standard one which has the function-call stack trace.
I attempted to set the shutdown function using register_shutdown_function, but that did not prevent the default error page (with stack trace) from displaying.
Thanks!
you can put your proccesses that might fail into a try block
try {
// assert this fails because you have some buggy code here
$foos=$fooService->getFoosByDateTime();
}catch(\Exception $e){
//you can catch the exception
$exceptionMessage= $e->getMessage();
$this->redirect("your_custom_route_to_error_page",{"error":$exceptionMessage});
}
You could enable catching Fatal errors and converting them into Exceptions, shown in Debug Component.
// If I remember correct Symfony Fullstack already does this
http://symfony.com/doc/current/components/debug/introduction.html
Then you could write a own Exception Handler, which catches and handles the exception in a user friendly way.

Make webservice exception show message only

I have a webservice, that is used by some asp.net application. When an exception occurs in the webservice, I want to display the exception message by doing someLabel.text = ex.Message. For some reason, when I do this, I get the entire description as follows instead of the Message only. Anyone knows how to do this without having to split it up in the application?
System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.Exception: This username is already taken. at WSRegistration.Service1.RegisterUser(String username, String psswd) in C:\Users\Korax\documents\visual studio 2010\Projects\Excercise2\WSRegistration\UserRegistration.asmx.cs:line 41 --- End of inner exception stack trace ---

Strange Request URLs in logged ASP.NET exceptions, but not in IIS logs

Getting unhandled exception event log messages for legitimate exceptions but the event log message includes noise in the request URL.
The noise is injected where uri escaped characters are. Noise like the apppool name, "An unhandled exception has occurred.", False and sometimes the request url itself recursively injected, sometimes a dozen times inside the url. The IIS logs don't show this injection, just the original url.
Here's one of the recursive examples:
Request URL: http://domain.com/Page.aspx?q=bransonAn unhandled exception has occurred.Chttp://domain.com/Page.aspx?q=bransonAn unhandled exception has occurred.Chttp://domain.com/Page.aspx?q=bransonAn unhandled exception has occurred.Chttp://domain.com/Page.aspx?q=branson%2C%20momomomo
The one somewhat unusual thing about the code is that it uses an exception filter which does some logging and then returns false, allowing the exception to go unhandled.
I've encountered the same issue as described above and after a few days on Google have come up with the what caused it (well for me anyway) and thought that I'd share - Even though this discussion is over a year old.
It was caused by spaces being included in the query string, which were getting changed to %20. When an exception was getting raised within the code it appears that IIS (or the Development Server in Visual Studio 2008) was, possibly, assuming that the %20 was a parameter to be passed in to the exception handler and building up the crazy looking Request URL - It was always contained 82 times within the log and no where I searched mentioned this.
In the web.config the encoding can be managed through the globalization section, but this didn't resolve our issue - It turns out that if you use RFC2396, then you don't get this issue. We're now replacing our spaces with a non-breakable space character and this is working so far in our testing.

Null Reference getting REMOTE_ADDR

I have an ASMX web service running under IIS7 in classic mode. This service has the following code:
try
{
env.ExternalIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
catch (Exception ex)
{
LogWriter.WriteError(ex);
env.ExternalIP="000.000.000.000";
}
This results in the following stack trace. I only modified the names of usercode call stack here to protect the innocent:
Message: An Exception of type: NullReferenceException occured in method: GetAdditionalServerVar
ExceptionMsg: Object reference not set to an instance of an object.
===Stack Trace===
at System.Web.Hosting.ISAPIWorkerRequestInProc.GetAdditionalServerVar(Int32 index)
at System.Web.Hosting.ISAPIWorkerRequestInProc.GetServerVariable(String name)
at System.Web.HttpRequest.AddServerVariableToCollection(String name)
at System.Web.HttpRequest.FillInServerVariablesCollection()
at System.Web.HttpServerVarsCollection.Populate()
at System.Web.HttpServerVarsCollection.Get(String name)
at System.Collections.Specialized.NameValueCollection.get_Item(String name)
at MyService.MyMethod()
I'm at a loss here as this is very basic plain vanilla code.
EDIT
This gets even stranger. I have added some basic code just wondering what server variables I can get at this point. This fails with the same exception when I try and get all the keys:
System.NullReferenceException: Object
reference not set to an instance of an
object. at
System.Web.Hosting.ISAPIWorkerRequestInProc.GetAdditionalServerVar(Int32
index) at
System.Web.Hosting.ISAPIWorkerRequestInProc.GetServerVariable(String
name) at
System.Web.HttpRequest.AddServerVariableToCollection(String
name) at
System.Web.HttpRequest.FillInServerVariablesCollection()
at
System.Web.HttpServerVarsCollection.Populate()
at
System.Web.HttpServerVarsCollection.get_AllKeys()
at MyService.MyHelper()
When I was looking at the framework code looks like this could happen when the array which caches the server variables isn't populated and it looks like this occurs when there a null pointer to some Context...which seems like a fairly core piece of the framework code.
I suppose it's time to burn up one of our support tickets with Microsoft.
Going through my old questions. I believe this was caused by a bug in either .net or IIS. Essentially, the web service was marked as Oneway. By doing so the user was disconnected before the handler was executed so unless you managed to access the Request variables prior to the handler executing you would encounter a null reference exception.
The workaround was to add an HTTP module which accessed the property earlier in the pipeline before the client was sent the response and the handler was executed.
Have you tried getting the ip directly from HttpContext.Current.Request.UserHostAddress?
It seems that it is not always populated depending on the proxies... http://haacked.com/archive/2006/10/11/A_Gotcha_Identifying_the_Users_IP_Address.aspx

Server cannot append header after HTTP headers have been sent?

I am getting the following warnings on the Event Log for a Asp.Net WebSite running on IIS 7.
Exception information:
Exception type: HttpException
Exception message: Server cannot append header after HTTP headers have been sent.
at System.Web.Hosting.ISAPIWorkerRequest.SendUnknownResponseHeader(String name, String value)
at System.Web.HttpResponse.WriteHeaders()
at System.Web.HttpResponse.Flush(Boolean finalFlush)
at System.Web.HttpRuntime.FinishRequest(HttpWorkerRequest wr, HttpContext context, Exception e)
I tried to debug the WebSite but it just does not show in debugger. The web page which has got this issue contains the following.
Its a content page with a Master page.
It has a grid inside an UpdatePanel which is Triggered by a Timer.
On the specified time grid data is refreshed.
Everytime this happens we see a new warning in the EventLog. What is the best way to go about this issue?
You have a control that is misbehaving. You may add headers at any point before any content is written to the response stream, after that point adding a header will throw.
The exception is being thrown deep so you will have to try Debug>Exceptions>Common Language Runtime Exeptions and check 'thrown'. It may now be possible to break on the exeption and examine the inner exception or trace the call stack and find out who is being bad.

Resources