为了获取当前已登录的用户,我使用以下代码:
string opl = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();
我在一个ASP.NET应用程序上工作,需要这些信息。因此,我将我的应用程序放在服务器上并尝试了上面的代码,然后我得到了字符串opl中的“Network Service”。我需要知道访问我的ASP.NET应用程序的PC的当前用户。
为了获取当前已登录的用户,我使用以下代码:
string opl = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();
我在一个ASP.NET应用程序上工作,需要这些信息。因此,我将我的应用程序放在服务器上并尝试了上面的代码,然后我得到了字符串opl中的“Network Service”。我需要知道访问我的ASP.NET应用程序的PC的当前用户。
简单回答是User = System.Web.HttpContext.Current.User
确保你的web.config拥有以下认证元素。
<configuration>
<system.web>
<authentication mode="Windows" />
<authorization>
<deny users="?"/>
</authorization>
</system.web>
</configuration>
System.Web.HttpContext.Current.User.Identity.Name
。 - NashwanSystem.Web.HttpContext.Current.User.Identity.Name
应该可以工作。
请按以下步骤检查托管您的站点的服务器上的IIS网站设置:
进入 IIS → Sites → 您的站点 → Authentication
现在检查是否禁用了匿名访问并启用了Windows身份验证。
现在,System.Web.HttpContext.Current.User.Identity.Name
应返回类似于此的内容:
域名\用户名
Membership.GetUser()
你的代码返回的是分配给ASP.NET的Windows账户。using System.Web.Security
Identity.IsAuthenticated
属性,然后像这样获取usr.UserName
:string userName = string.Empty;
if (System.Web.HttpContext.Current != null &&
System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
{
System.Web.Security.MembershipUser usr = Membership.GetUser();
if (usr != null)
{
userName = usr.UserName;
}
}
HttpContext.Current.User.Identity.Name
不要想得太远。
如果你使用ASP.NET MVC开发,用户只是Controller
类的一个属性(property of the Controller
class)。因此,如果你在一些模型中迷失了寻找当前用户的信息,请尝试退回到控制器中获取相关信息。
在控制器中,只需使用:
using Microsoft.AspNet.Identity;
...
var userId = User.Identity.GetUserId();
...
使用字符串作为 userId
。
using System.Web;
WindowsIdentity user;
user = HttpContext.Current.Request.LogonUserIdentity;
我遇到了同样的问题。
这是对我有用的解决方法:
NTLM必须是最上面的。 进一步的Web.config修改,请确保您已经拥有或添加了以下内容(如果不存在):
<system.web>
<authentication mode="Windows" />
<identity impersonate="true"/>
</system.web>
<!-- you need the following lines of code to bypass errors, concerning type of Application Pool (integrated pipeline or classic) -->
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
</system.webServer>
请看下面对节点 <system.web> 和 <system.webServer> 的合法解释:
<system.web>和<system.webServer>之间的区别是什么?
当然,你可以通过以下方式获取用户名:
//I am using the following to get the index of the separator "\\" and remove the Domain name from the string
int indexOfSlashChar = HttpContext.Current.User.Identity.Name.IndexOf("\\");
loggedInWindowsUserName = HttpContext.Current.User.Identity.Name.Substring(indexOfSlashChar + 1);