[英]how to get windows login name in c#
我有一个使用C#的Web应用程序,我想在该应用程序中获取用户的登录计算机名。 该页面将由另一个网址调用。
我尝试了几种方法,但没有获得想要的结果。 这是我的代码:
1. txtBookBy.Text = WindowsIdentity.GetCurrent().Name;
2. txtBookBy.Text = User.Identity.Name;
3. txtBookBy.Text = Request.ServerVariables[5];
4. txtBookBy.Text = System.Environment.UserName;
5. txtBookBy.Text = Request.ServerVariables["LOGON_USER"];
6. txtBookBy.Text = Request.QueryString["user"];
这是我通过另一个网址致电时的结果。
1. txtBookBy.Text = "compName\ASPNET";
2. txtBookBy.Text = "";
3. txtBookBy.Text = "";
4. txtBookBy.Text = "ASPNET";
5. txtBookBy.Text = "";
6. txtBookBy.Text = @Variable;
这就是我在Visual Studio中运行时的结果。
1. txtBookBy.Text = "PT\asromi";
2. txtBookBy.Text = "PT\asromi";
3. txtBookBy.Text = "PT\asromi";
4. txtBookBy.Text = "asromi";
5. txtBookBy.Text = "PT\asromi";
6. txtBookBy.Text = @Variable;
我想要的结果:当我通过另一个网址致电时,结果类似“ asromi”
有人告诉我重新配置IIS。
但是,我真的是IIS的新手。 请详细说明技术,我该怎么做。
您可以通过以下方式在Windows身份验证下获取用户的WindowsIdentity对象:
WindowsIdentity identity = HttpContext.Current.Request.LogonUserIdentity;
然后您可以获取有关用户的信息,例如identity.Name。
请注意,您需要为这些代码使用HttpContext,并且应在Web.config
文件中启用WindowsAuthentication
<security>
<authentication>
<anonymousAuthentication enabled="false" />
<windowsAuthentication enabled="true" />
</authentication>
</security>
尝试使用以下代码
public class DNSHelper
{
/// <summary>
/// Gets the username.
/// </summary>
/// <param name="request">The request.</param>
/// <returns></returns>
public static string GetUsername(System.Web.HttpRequest request)
{
try
{
return request.LogonUserIdentity.Name;
}
catch (InvalidOperationException ioex)
{
if (System.Web.HttpContext.Current.User != null)
{
return System.Web.HttpContext.Current.User.Identity.Name;
}
else
{
return string.Empty;
}
}
}
}
例:
var username = DNSHelper.GetUsername(System.Web.HttpContext.Current.Request);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.