2016-09-30 175 views
0

我在.Net Framework 4.0中用Default.aspx页面创建了一个测试Web应用程序。我只是想用户O访问网络ID所以我写了下面的背后Default.aspx中的代码的代码,但得到空值,当我运行应用程序按F5:如何访问asp.net 4.0中的网络ID

string username = Page.User.Identity.Name; 

,并在web.config中启用Windows身份验证模式:

<authentication mode="Windows" /> 

然后我试着在控制台应用程序下面,我能得到我的网络ID:

Console.WriteLine(Environment.UserName); 

我失去了在Web应用程序中的任何配置步骤。

感谢

回答

0

这是生产代码,我使用的是将获得的用户信息,并检查AD组了。

创建一个变量,将初始化该类并访问您需要的任何方法,它将返回您的AD \ Network信息。

using System.DirectoryServices.AccountManagement; 
using System.Security.Principal; 

public class IsUserInRole 
{ 

public static bool IsInGroup(string groupName) 
{ 
    var myIdentity = GetUserIdWithDomain(); 
    var myPrincipal = new WindowsPrincipal(myIdentity); 
    return myPrincipal.IsInRole(groupName); 
} 


public bool IsInGroup(List<string> groupNames) 
{ 
    var myIdentity = GetUserIdWithDomain(); 
    var myPrincipal = new WindowsPrincipal(myIdentity); 

    if (groupNames.Any(@group => myPrincipal.IsInRole(@group) == true)) 
    { 
     return true; 
    } 
    else 
    { 
     return false; 
    } 

} 

public static WindowsIdentity GetUserIdWithDomain() 
{ 
    WindowsIdentity myIdentity = WindowsIdentity.GetCurrent(); 
    return myIdentity; 
} 

public static string GetUserId() 
{ 
    var id = GetUserIdWithDomain().Name.ToString().Split("\\"); 
    return id(1); 
} 


public static string GetUserDisplayName() 
{ 
    var id = GetUserIdWithDomain().Name.ToString().Split("\\"); 

    var dc = new PrincipalContext(ContextType.Domain, id(0)); 
    var adUser = UserPrincipal.FindByIdentity(dc, id(1)); 
    return adUser.DisplayName; 

} 


} 

编辑1

Gven您的意见重新回到它您需要将以下添加到您的web.config文件

<system.web> 
    <identity impersonate="true" /> 
    ... 
    </system.web> 

然后在IIS中也进入您的网站\用户然后应用程序转到授权,然后禁用匿名用户,启用ASP.Net模拟和Windows身份验证

enter image description here

编辑2

当您遇到的挑战进行访问,这意味着你没有正确的权限设置

+0

我写了下面的Page_Load事件 “的Response.Write(‘用户名:’行+ WindowsIdentity.GetCurrent()名称)。”并在IIS中托管网站。我在页面中收到以下消息: 用户名:IIS APPPOOL \ TestWeb 相反,它应该显示我的域名和网络ID,例如 用户名:mydomain \ mynetowrkid – Sukhjeevan

+0

好的,那是什么给你的?此外你的IIS设置重新认证你的用户在网站上。 –

+0

在此之后获得Windows身份验证我没有在IIS下 匿名身份验证残疾人 ASP.NET模拟残疾人 窗体身份验证残疾人 Windows身份验证启用 并在web.config中<认证模式=“窗口” /> 现在如果我浏览网站,我会弹出Windows Security,并询问我的Windows凭据。我试图用我的Windows登录详细信息,但去以下消息: 用户名:MYDOMAIN \ mynetworkid 密码:我的Windows密码 HTTP错误401.1 - 未经授权 – Sukhjeevan