2

My codes below don't have any errors during the compile time but when I open the page an error occur at the Guid currentUserId = (Guid)currentUser.ProviderUserKey; stating that Object reference not set to an instance of an object.

foreach(DataRowView ProfileInfo in UserProfileDataSource.Select(DataSourceSelectArguments.Empty))
            {
              //Some codes where I display data from database
            }



protected void UserProfileDataSource_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
    {
        MembershipUser currentUser = Membership.GetUser();

        Guid currentUserId = (Guid)currentUser.ProviderUserKey;

        e.Command.Parameters["USERID"].Value = currentUserId;
    }

and here is my SQLDataSource

<asp:SqlDataSource ID="UserProfileDataSource" runat="server" 
            ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
            onselecting="UserProfileDataSource_Selecting" 
            ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>"


            SelectCommand="SELECT &quot;TITLE&quot;, &quot;FAMILYNAME&quot;, &quot;GIVENNAME&quot;, &quot;MIDDLENAME&quot;, &quot;POSITION&quot;, &quot;INSTITUTIONNAME&quot;, &quot;USERID&quot;, &quot;REGISTEREDDATE&quot; FROM &quot;MEMBERINFO&quot; WHERE (&quot;USERID&quot; = ?)">
            <SelectParameters>
                <asp:Parameter Name="USERID" Type="Object" />
            </SelectParameters>
        </asp:SqlDataSource>

Ernie

Ernie Ahsir
  • 27
  • 2
  • 7
  • Is currentUser null? Have you checked that Request.IsAuthenticated is true? – kmp Mar 11 '12 at 08:50
  • thanks for your fast reply. I think it is not null because my scenario is that the code will execute every time they visit there profile after logging in. I haven't checked the Request.IsAuthenticated, can you please give me an example of it. – Ernie Ahsir Mar 11 '12 at 09:00
  • This really looks like currentUser is null to me (from looking at what you changed in the answer to the question below it would indicate that being the case). How about putting a break point on the line Guid currentUser = ... and then in the watch window check System.Threading.Thread.CurrentPrincipal.Identity.Name and then make sure that that is the username of the user you are logged in as. – kmp Mar 11 '12 at 09:31

4 Answers4

4

you should check to make sure that currentUser is not null before trying to access it:

if ( currentUser != null )
{
/* do stuff here */
}
else
{
/* do something else, like show an error message perhaps */
}
Muad'Dib
  • 28,542
  • 5
  • 55
  • 68
  • Thank you for tour fast reply. I tried using the code that you posted and I do it like this `protected void UserProfileDataSource_Selecting(object sender, SqlDataSourceSelectingEventArgs e) { // Get a reference to the currently logged on user MembershipUser currentUser = Membership.GetUser(); if (currentUser != null) { Guid currentUserId = (Guid)currentUser.ProviderUserKey; e.Command.Parameters["USERID"].Value = currentUserId; } }` – Ernie Ahsir Mar 11 '12 at 09:01
  • you can do the check however you like, you just have to make sure that its not null before you try to use it. :) – Muad'Dib Mar 11 '12 at 09:03
  • but then the same error occurred on the `UserProfileDataSource.Select(DataSourceSelectArguments.Empty)` line – Ernie Ahsir Mar 11 '12 at 09:04
  • either the UserProfileDataSource is null or the Select is returning null – Muad'Dib Mar 11 '12 at 09:05
0

try this code:

 string username =  HttpContext.Current.User.Identity.Name;

 if(!string.IsNullOrEmpty(username))
 {
 MembershipUser currentUser = Membership.GetUser(username);
 Guid currentUserId = new Guid(currentUser.ProviderUserKey.ToString());

 }
Jignesh Rajput
  • 3,538
  • 30
  • 50
0

You appear to be allowing anonymous users to access a page that requires a logged in user. You can't get the user if they haven't logged in yet.

Security consists of two parts, authorization and authentication. Authentication is logging in, but authorization is denying access to pages to unauthorized users (such as ones that have not yet logged in, or do not have the correct roles assigned to them).

If your page depends on an authenticated user, then you should deny anonymous users access. If the page does not depend on an authenticated user, but merely makes use of member information if they are authenticated, then you need to guard against calling member functions (or anything that uses member data) if the user is not authenticated.

Erik Funkenbusch
  • 92,674
  • 28
  • 195
  • 291
-1

The issue is Bad code. Try these steps:- In your website, set the "Start page" to the correct "login" page. Once you login, correctly and then land on the page, you should be able to access this property. You may get into the same error if you click logout button and the landing page might be referring to this membership information.

So the work-around is simple. 1.Set the start page correctly. 2.Handle the 2 cases:- user is logged in and user is not logged in efficiently. an example is as below:-

protected void Page_Load(object sender, EventArgs e) {

     if (Membership.GetUser() == null)
     { Label1.Text = "";
     Label_TotalCoxxxxxxxxx.Text = "";
     Label_TotalSuxxxxxxxxx.Text  ="";
     }
     else {
        string loggedinuser = Membership.GetUser().ToString();
        Label1.Text = loggedinuser;
        Label_TotalCoxxxxxxxxx.Text = "Total of xxxxxxxxxx Added in the current Month:-";
        Label_TotalSuxxxxxxxxx.Text = "Total of yyyyyyyyyy done in the current Month:-";
     }
}