GibboK
GibboK

Reputation: 73918

The parameter 'username' must not be empty

I have create a method that should return an attributes soredin Active Directory for a logged in User using Membership.

I receive this error The parameter 'username' must not be empty. any idea how to solve it?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.Security;
using System.DirectoryServices.AccountManagement;
using System.Threading;

   public static string SetGivenNameUser()
    {
        string givenName = string.Empty;
        MembershipUser user = Membership.GetUser();
        PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
        UserPrincipal userP = UserPrincipal.FindByIdentity(ctx, user.UserName);
        if (userP != null)
            givenName = userP.GivenName;
        return givenName;
    }

STACK

ArgumentException: The parameter 'username' must not be empty.
Parameter name: username]
   System.Web.Util.SecUtility.CheckParameter(String& param, Boolean checkForNull, Boolean checkIfEmpty, Boolean checkForCommas, Int32 maxSize, String paramName) +2386569
   System.Web.Security.ActiveDirectoryMembershipProvider.CheckUserName(String& username, Int32 maxSize, String paramName) +30
   System.Web.Security.ActiveDirectoryMembershipProvider.GetUser(String username, Boolean userIsOnline) +86
   System.Web.Security.Membership.GetUser(String username, Boolean userIsOnline) +63
   System.Web.Security.Membership.GetUser() +19

Upvotes: 0

Views: 3805

Answers (2)

GibboK
GibboK

Reputation: 73918

I share the code which solved my problem. My issue was that I was calling SetGivenNameUser when the user was not logged in so I have to make an adjustment. Thanks all for your suggestions.

   public static string SetGivenNameUser()
    {
        string givenName = string.Empty;
        string currentUser = HttpContext.Current.User.Identity.Name;
        // If the USer is logged in
        if (!string.IsNullOrWhiteSpace(currentUser))
        {
            MembershipUser user = Membership.GetUser();
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
            UserPrincipal userP = UserPrincipal.FindByIdentity(ctx, user.UserName);
            if (userP != null)
                givenName = userP.GivenName;
        }
        return givenName;
    }

Upvotes: 1

Dave Alperovich
Dave Alperovich

Reputation: 32500

Except when you just set authorization, in which case the httpcontext object needs to be reset, the most reliable way to get username is

HttpContext.Current.User.Identity.Name

so, refactoring your code would look like this:

UserPrincipal userP = UserPrincipal.FindByIdentity(ctx, HttpContext.Current.User.Identity.Name);

Reason for this is, some objects have their own local 'hooks' into membership. And sometimes those hooks haven't been filled my the httpcontext object yet.

Upvotes: 3

Related Questions