有没有办法在ASP.NET Web服务方法中获取请求用户的ID?

时间:2010-04-30 18:19:17

标签: asp.net soap

我知道这可能是不可能的,但我希望能够从ASP.NET Web服务方法中获取Request用户ID。到目前为止,我已尝试User.Identity.NameContext.Request.LogonUserIdentity.NameRequest.ServerVariables["AUTH_USER"]Request.ServerVariables["LOGON_USER"]。我在这里倾斜风车,还是有一些超级简单的东西我不知道?

1 个答案:

答案 0 :(得分:0)

那么,用户ID是什么意思?

如果他们通过Windows身份验证进行身份验证,User.Identity会为您提供与该用户对应的WindowsIdentity对象。

如果您希望对应于经过身份验证的用户的用户ID“神奇地”显示在您的页面中,您也可以这样做!在您的Global.asax中,有一个名为Application_AuthenticateRequest的函数,您可以实现该函数以获取传递给应用程序的任何标识,并将其转换为可从您的页面访问的基于IPrincipal的对象。

因此,当您实现AuthenticateRequest()时,您可以使用HttpContext.Current.User.Identity.Name,并使用它来从您的数据库中查找您的用户ID。从那里,您构造自己的IPrincipal派生对象,并将HttpContext.Currrent.User引用设置为您创建的对象。然后,您可以将页面中的“用户”转换为您创建的对象并读取用户ID。我们一直这样做。这是一些示例代码(实际上缓存了Principal对象,因此您不必在每次请求时都转到DB):

protected void Application_AuthenticateRequest(object sender, EventArgs e) {
        try {
            IIdentity myIdentity = HttpContext.Current.User.Identity;
            MyPrincipal myPrincipal = (MyPrincipal)HttpContext.Current.Cache[myIdentity.Name];

            if (myPrincipal == null) {
                    myPrincipal = (MyPrincipal)GetPrincipalFromDatabase(HttpContext.Current.User.Identity);
                    HttpContext.Current.Cache.Insert(myIdentity.Name, myPrincipal, null, DateTime.Now.AddMinutes(1), TimeSpan.Zero);                
            }

            HttpContext.Current.User = myPrincipal;
        }
        catch (SecurityException) {
            HttpContext.Current.User = null;
        }
        catch (Exception ex) {
            Trace.WriteLine("Could not validate your user.");
        }
    }