参数“用户名”不得为空
本文关键字:用户名 用户 参数 | 更新日期: 2023-09-27 17:57:15
我创建了一个方法,该方法应该为使用成员资格的登录用户返回属性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
除非你只是设置了授权,在这种情况下,httpcontext 对象需要重置,获取用户名的最可靠方法是
HttpContext.Current.User.Identity.Name
因此,重构代码将如下所示:
UserPrincipal userP = UserPrincipal.FindByIdentity(ctx, HttpContext.Current.User.Identity.Name);
这样做的原因是,某些对象有自己的本地"钩子"成员资格。有时这些钩子还没有填满我的httpcontext对象。
我分享了解决我问题的代码。我的问题是我在用户未登录时调用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;
}