在ASP.NET中获取Windows用户名,无需使用System.Web。

7 浏览
0 Comments

在ASP.NET中获取Windows用户名,无需使用System.Web。

我有一个用于ASP.NET(Windows身份验证)和winforms项目的报告dll。有时它需要用户名,所以如果它在ASP.NET中运行,它会使用:

System.Web.HttpContext.Current.User.Identity.Name;

而在Windows中,它会使用:

WindowsIdentity.GetCurrent().Name

现在,我正在尝试转移到.NET 4 Client Profile,所以我需要避免在报告dll中引用System.Web。是否有一种在dll在ASP.NET中运行时获取Windows用户名的替代方法,而不使用System.Web?目前我唯一看到避免使用System.Web的方法是将用户名作为参数传递,这将在每个报告中调整起来很麻烦。

0
0 Comments

问题出现的原因:在ASP.NET中获取Windows用户名时,常用的方法是使用Environment.UserName,该方法位于System命名空间中。然而,如果在IIS网站中使用AD账户来运行,使用Environment.UserName将会获取到运行网站的账户,而不是访问网站的用户。

解决方法:如果想要获取访问网站的用户的Windows用户名,可以通过从请求上下文中获取身份验证凭据来实现。下面是一种解决方法:

using System.Security.Principal;
// 获取Windows用户名
public string GetWindowsUserName()
{
    string username = null;
    
    // 获取当前请求的上下文
    HttpContext context = HttpContext.Current;
    
    // 检查上下文是否存在
    if (context != null)
    {
        // 获取用户身份验证信息
        WindowsIdentity identity = context.Request.LogonUserIdentity;
        
        // 检查身份验证信息是否存在
        if (identity != null)
        {
            // 获取Windows用户名
            username = identity.Name;
        }
    }
    
    return username;
}

使用上述代码,可以通过调用GetWindowsUserName()方法来获取访问网站的用户的Windows用户名。这种方法可以解决在ASP.NET中获取Windows用户名的问题,而不受运行网站的账户影响。

0
0 Comments

问题的原因是需要获取ASP.NET中经过身份验证的最终用户的Windows用户名,而不是运行网站的Web服务器的用户。然而,使用Thread类的CurrentPrincipal属性仅返回运行网站的Web服务器用户,而不是经过身份验证的最终用户。

解决方法是使用HttpContext类的User属性来获取经过身份验证的最终用户的Windows用户名。以下是解决方法的代码示例:

using System.Web;
string userName = HttpContext.Current.User.Identity.Name;

这样就可以获取经过身份验证的最终用户的Windows用户名了。

0
0 Comments

在ASP.NET中,System.Web命名空间是可用的。您可以在应用程序中使用它。除此之外,您还可以使用Membership提供程序来验证或获取当前用户名。

但是,如果您希望将底层dll添加到WinForms的客户端配置文件中以供使用,您将无法添加System.Web引用。

这可能会导致一个问题:在ASP.NET中如何获取Windows用户名而不使用System.Web?

解决方法如下:

1. 使用WindowsIdentity类来获取Windows用户名。这是一个在System.Security.Principal命名空间下的类。

using System.Security.Principal;

...

WindowsIdentity identity = WindowsIdentity.GetCurrent();

string username = identity.Name;

2. 使用WMI(Windows Management Instrumentation)来获取Windows用户名。这需要使用System.Management命名空间。

using System.Management;

...

string username = string.Empty;

ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem");

foreach (ManagementObject managementObject in searcher.Get())

{

username = managementObject["UserName"].ToString();

break;

}

这些方法可以在ASP.NET应用程序中获取Windows用户名而不使用System.Web。您可以根据自己的需求选择其中的一种方法。

0