0

メンバーシップを使用して、ログインしているユーザーの 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 に答える