簡體   English   中英

從HttpModule調用Membership.GetUser()失敗

[英]Membership.GetUser() fails when called from an HttpModule

我正在從ASP.NET應用程序的Global.asax文件中的Application_Error()方法內部調用Membership.GetUser() ,以便記下一些日志信息。

但是,如果HttpModule內部發生錯誤,它似乎會失敗。 正常嗎 在ASP.NET中執行HttpModules時,成員資格還沒有准備好嗎? 難道我做錯了什么?

它引發“對象引用未設置為對象的實例”。 異常(位於System.Web.Security.Membership.GetCurrentUserName(),位於System.Web.Security.Membership.GetUser())。

會話尚不存在,成員資格存儲其信息。 FormsAuthentication.SetAuthCookie設置一個cookie,但該cookie被讀取。

我將查看您的Global.asax.cs中的兩個事件(或從HttpApplication派生的任何類)

  • AuthenticateRequest
  • 的AcquireRequestState

您可以從Global的Application_Error內部使用HttpApplication.User。 例如:

User.Identity.Name

這是我使用的一個:

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM