tags:

views:

371

answers:

2

I'm calling Membership.GetUser() from inside Application_Error() method in Global.asax file in an ASP.NET application in order to write down some log information.

However, it seems to fail if an error happens inside an HttpModule. Is it normal? Isn't Membership ready while executing HttpModules in ASP.NET? Am I doing something wrong?

It throws an "Object reference not set to an instance of an object." exception (at System.Web.Security.Membership.GetCurrentUserName(), at System.Web.Security.Membership.GetUser()).

A: 

You can use the HttpApplication.User from inside Global's Application_Error. eg:

User.Identity.Name

Here's one I use:

protected void Application_Error(object sender, EventArgs e)
{
    try
    {
        Exception lastError = Server.GetLastError().GetBaseException();
        if (lastError is HttpException && ((HttpException)lastError).GetHttpCode() == 404)
            return;

        if (Request.UrlReferrer != null)
            lastError.Data.Add("Referrer", Request.UrlReferrer);
        if (Request.RawUrl != null)
            lastError.Data.Add("Page", Request.RawUrl);
        if (Request.UserHostAddress != null)
            lastError.Data.Add("Client IP", Request.UserHostAddress);
        if (Request.UserAgent != null)
            lastError.Data.Add("UserAgent", Request.UserAgent);
        if (User != null && User.Identity != null && !string.IsNullOrEmpty(User.Identity.Name))
            lastError.Data.Add("User", User.Identity.Name);

        Log.Error("Application_Error trapped at Global.asax", lastError);
    }
    // ReSharper disable EmptyGeneralCatchClause
    catch { } // Intentionally empty catch clause as this is the catchall exception handler. If it fails, the sky has fallen.
    // ReSharper restore EmptyGeneralCatchClause
}
grenade
+2  A: 

Session doesn't exist yet, where membership stores its information. FormsAuthentication.SetAuthCookie sets a cookie but that cookie is read up.

I would look at two events in your Global.asax.cs (or whatever class derives from HttpApplication)

  • AuthenticateRequest
  • AcquireRequestState