0

所以我遇到了这个问题,有人试图加载这个没有电子邮件地址的页面,我很难找到解决办法。

//getting email address for current user
    IIdentity id = WindowsIdentity.GetCurrent();
    WindowsIdentity winId = id as WindowsIdentity;
    if (id != null)
    {
        userName = winId.Name;

        string userInQuestion = userName.Split('\\')[1];
        string myDomain = userName.Split('\\')[0]; // this is the domain that the user is in
        // the account that this program runs in should be authenticated in there                    

        using (HostingEnvironment.Impersonate())
        {
            DirectoryEntry entry = new DirectoryEntry("LDAP://" + myDomain);
            DirectorySearcher adSearcher = new DirectorySearcher(entry);

            adSearcher.SearchScope = SearchScope.Subtree;
            adSearcher.Filter = "(&(objectClass=user)(samaccountname=" + userInQuestion + "))";
            SearchResult userObject = adSearcher.FindOne();
            if (userObject != null)
            {
                string[] props = new string[] { "mail"};
                {
                    foreach (string prop in props)
                    {
                        if (userObject.Properties[prop][0].ToString() != "")
                        {
                            CurrentUserEmail = userObject.Properties[prop][0].ToString();
                        }
                        else
                        {
                            CurrentUserEmail = "";
                        }
                    }

                }
            }

        }
    }

这是我得到的堆栈跟踪,我知道有些提交此表单的人可能没有电子邮件地址,但我似乎无法找到解决该问题的方法。那里的 if else 语句是我最近的尝试,但错误仍然存​​在。

在此处输入图像描述

4

2 回答 2

3

你的问题[0]userObject.Properties[prop][0].ToString()

如果数组为空;即没有元素,您将收到错误消息。尝试

CurrentUserEmail = "";
var propertyArray = userObject.Properties[prop];
if (propertyArray.Lenght > 0) CurrentUserEmail = propertyArray[0] as string;
于 2013-11-08T15:15:10.243 回答
0

为什么不捕获异常并将电子邮件地址分配给 catch 块中的“”?

于 2013-11-08T15:06:47.480 回答