Code producing System.NullReferenceException error for Membership.GetUser(). This is VB.Net (ASP.Net 4)
I have a Default.aspx page that is not static. I have added functionality with datalist and sqldatasources. When a user logins he/she will see items like saved workouts, saved equipment, total replys, etc... This is based on getting the currently logged in user UserID. Quite simply this works great when the user is logged in. However, I do not want to force a user to login to view the Default page because it does have functionality on it that does not require login. When a user is not logged in of course I receive the [System.NullReferenceException] error. I understand the error well but I do not know how to code to fix it. That is where I need help. I will admit I am more designer than developer. However, I do know the exception error I am receivving is caused by me not setting a value in my code when a user is not logged in. I do not know how to do that and have for a week made unsuccessful attempts at writing the code.
Both sets of code below compile for VB.Net/ASP.Net 4/Visual Studio 2010 without errors. However, I still get the System.NullRe开发者_StackOverflow中文版ferenceException error if not logged in. I know it can be done but I do not know the right syntax. If you can help please insert you code in mine or write it out. JUST TELLING ME WHERE TO GO TO FIND AN ANSWER WON'T HELP. I HAVE DONE THAT FOR 7 STRAIGHT DAYS. I APPRECIATE OUR HELP.
Partial Class _Default Inherits System.Web.UI.Page
Protected Sub SqlDataSource4_Selecting(ByVal sender As Object, ByVal e As SqlDataSourceCommandEventArgs) Handles SqlDataSource4.Selecting
Dim MemUser As MembershipUser
MemUser = Membership.GetUser()
If Not MemUser Is DBNull.Value Then
UserID.Text = MemUser.ProviderUserKey.ToString()
e.Command.Parameters("@UserId").Value = MemUser.ProviderUserKey.ToString()
End If
End Sub
-------------------------------------ORIGINAL CODE-------------------------------
Partial Class _Default Inherits System.Web.UI.Page
Protected Sub SqlDataSource4_Selecting(ByVal sender As Object, ByVal e As SqlDataSourceCommandEventArgs) Handles SqlDataSource4.Selecting
Dim MemUser As MembershipUser
MemUser = Membership.GetUser()
UserID.Text = MemUser.ProviderUserKey.ToString()
e.Command.Parameters("@UserId").Value = MemUser.ProviderUserKey.ToString()
End Sub
If MemUser IsNot Nothing Then
UserID.Text = MemUser.ProviderUserKey.ToString()
e.Command.Parameters("@UserId").Value = MemUser.ProviderUserKey.ToString()
End If
Note that I write Nothing instead of DBNull.Value.
I see another problem here, though: If MemUser is nothing, you do not set the @UserId parameter of your query. This might cause a problem for your query.
DBNul.Value
is not the same as Nothing
.
Change it to
If MemUser IsNot Nothing Then
精彩评论