我创建了一个方法,该方法应该使用Membership返回登录用户的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;
}
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
答案 0 :(得分:3)
除非您只是设置授权,在这种情况下需要重置httpcontext对象,获取用户名的最可靠方法是
HttpContext.Current.User.Identity.Name
所以,重构代码看起来像这样:
UserPrincipal userP = UserPrincipal.FindByIdentity(ctx, HttpContext.Current.User.Identity.Name);
原因是,某些对象有自己的本地“钩子”成为成员资格。有时这些钩子还没有填充我的httpcontext对象。
答案 1 :(得分: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;
}