Matt Matt - 1 year ago 109
ASP.NET (C#) Question

How to get "sender" parameter's properties of Application_Error (in Global.ASAX)?

I am currently writing a generic error handler with logging for an application, which should extract useful information from the sender object.

As you already know, the Application_Error handler in Global.asax is defined as follows:

protected void Application_Error(Object sender, EventArgs e)

When I set a breakpoint inside of this method, I am getting through the locals window a lot of useful information from the sender:

In the type column, Visual Studio suggests the object is of type
, but this seems to be an artificial type because when I am trying to cast it like

var senderInfo = (ASP.global_asax)sender;

I am getting the following error:

CS0246: The type or namespace 'ASP' could not be found (are you missing a using directive or an assembly reference?)

So there are 2 questions related with "auto"-casting:

  1. Is there a way to cast
    into a suitable class type containing all the info the Locals window is showing? (Note that I don't require the static and non-public members)

  2. Likewise, can this be achieved for the exception object as well? (You can see in the screen shot that
    is of type System.Exception, but the exact type is
    . This could be especially useful for
    because here we're getting the real info about the reason why this exception occurred.)

    var exc = Server.GetLastError();
    var innerExc = exc.InnerException;

Note that this question "how to convert the sender to the best-fitting object type so all members can be accessed?" occurred while developing an
application, but the answer is not limited to it, it can be useful for any C# development.

N.B. I found some similar questions in Stackoverflow (here and there) but they are not duplicates because they are dealing with different topics.

Answer Source

You can use System.Web.HttpApplication for this.

Sample debug image

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download