0

我创建了一个方法,该方法应该为使用会员资格的登录用户返回属性 soredin Active Directory。

我收到此错误The parameter 'username' must not be empty.任何想法如何解决它?

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;
    }

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
4

2 回答 2

3

除非你只是设置了授权,在这种情况下需要重置 httpcontext 对象,最可靠的获取用户名的方法是

HttpContext.Current.User.Identity.Name

因此,重构您的代码将如下所示:

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

这样做的原因是,一些对象有自己的本地“挂钩”成员。有时这些钩子还没有被我的 httpcontext 对象填充。

于 2013-02-04T07:15:48.450 回答
1

我分享了解决我的问题的代码。我的问题是当用户未登录时我正在调用 SetGivenNameUser,因此我必须进行调整。谢谢大家的建议。

   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;
    }
于 2013-02-04T07:30:49.333 回答