Global.asax içerisinde HttpContext.Current.User.Identity nesnesine erişirken hata

alattin (16999) 10 yıl önce sordu

Asp.net'de Global.asax içerisinde  Current.User.Identity nesnesine erişirken, aşağıdaki hatayı alıyorsanız, Current.User.Identity nesnesine yanlış yerden erişmeye çalışıyor olabilirsiniz.

Server Error in '/' Application.

Nesne başvurusu bir nesnenin örneğine ayarlanmadı.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Nesne başvurusu bir nesnenin örneğine ayarlanmadı.

Toplam 1 cevap


alattin (16999) 10 yıl önce cevapladı

Asp.net'de Global.asax içerisinde  Current.User.Identity nesnesine erişirken, "Nesne başvurusu bir nesnenin örneğine ayarlanmadı." hatası alıyorsanız Current.User.Identity nesnesi henüz oluşturulmamış ve siz Current.User.Identity nesnesine erişmeye çalışıyorsunuz demektir.

Global.asax içerisinde Application_Start içerisinde Current.User.Identity nesnesine erişemezsiniz. Uygulamanız yeni başlamaktadır ve henüz Current.User.Identity nesnesi erişilebilir değildir.

protected void Application_Start()
        {
}

Bu sebepten Current.User.Identity nesnesine Session_Start metodunda erişmek daha doğru bir yaklaşımdır.

Global.asax içerisine Session_Start metodunu tanımlayın ve Current.User.Identity nesnesine Session_Start içerisinden erişin.

 protected void Session_Start(Object sender, EventArgs e)
        {
            var userId = HttpContext.Current.User.Identity.Name;
        }

gibi.