0

我正在开发一个 MVC 应用程序,我有一个获取当前登录用户密码信息的例程,它在我的 PC 上运行良好,但是当我将我的应用程序发布到域上的实时服务器时,我似乎无法以访问 AD 信息。我在当前运行的 asp.net web 应用程序中使用了非常相似的代码,它工作得很好。我比较了两个应用程序的安全设置,它们看起来相同。这是例程:

 public int GetPasswordExpiration()
    {
        PrincipalContext domain = new PrincipalContext(ContextType.Domain);
        string currUserName = WindowsIdentity.GetCurrent().Name;
        UserPrincipal currLogin = UserPrincipal.FindByIdentity(domain, currUserName);
        DateTime passwordLastSet = currLogin.LastPasswordSet.Value; //here is where it chokes***
        int doyPasswordSet = passwordLastSet.DayOfYear;
        int doy = DateTime.Today.DayOfYear;
        int daysSinceLastset = (doy - doyPasswordSet);
        int daysTilDue = (120 - daysSinceLastset);
        return (daysTilDue);

    }

我是域的管理员,所以我认为我有一个应用程序权限问题,但由于失败的应用程序与工作应用程序具有相同的权限,我不确定下一步该往哪里看。任何帮助表示赞赏。

4

1 回答 1

0

我正在回答我自己的问题,因为我想发布有效的代码。Wiktor Zychla 在询问 WindowsIdentity.GetCurrent().Name 是否应用于应用程序池的身份而不是登录用户时指出了这一点。事实上,它确实做到了,感谢 Wiktor!

这是修改后的代码。我确实改变了获取用户身份的方式(解释如下)。

控制器代码:

using MyProject.Utilities;  // Folder where I created the CommonFunctions.cs Class

var cf = new CommonFunctions();
string user = User.Identity.Name;
ViewBag.PasswordExpires = cf.GetPasswordExpiration(user);

CommonFunctions 中的代码

public int GetPasswordExpiration(string user)
    {
        PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
        UserPrincipal currLogin = UserPrincipal.FindByIdentity(ctx, user);
        DateTime passwordLastSet = currLogin.LastPasswordSet.Value;
        int doyPasswordSet = passwordLastSet.DayOfYear;
        int doy = DateTime.Today.DayOfYear;
        int daysSinceLastset = (doy - doyPasswordSet);
        int daysTilDue = (120 - daysSinceLastset);
        return (daysTilDue);

    }

让我想到的一件事是,我决定只运行控制器中的所有代码,当我这样做时,我得到了一条红色波浪线,上面写着“WindowsIdentity 的名称在此上下文中不存在”:

字符串 currUserName = WindowsIdentity .GetCurrent().Name;

此外,我在 Controller 中检索 User.Identity.Name 并将其传递给函数的原因是,一旦我开始工作并想要精简我的控制器,我试图在函数中获取 User.Identity.Name 但我得到了在此行中的用户下另一个带有相同消息的红色波浪线: string user = User.Identity.Name; 所以我认为这是一个 .net 的东西,只是在控制器中获取 User.Identiy.Name ,将它传递给函数,一切都很好。这个真的考验了我的耐心,我希望这篇文章可以帮助别人。

于 2012-06-13T00:57:26.553 回答