代码之家  ›  专栏  ›  技术社区  ›  AJ.

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

  •  0
  • AJ.  · 技术社区  · 15 年前

    我知道这可能是不可能的,但我希望能够从ASP.NET web服务方法中获取请求用户ID。到目前为止,我已经试过了 User.Identity.Name , Context.Request.LogonUserIdentity.Name Request.ServerVariables["AUTH_USER"] Request.ServerVariables["LOGON_USER"]

    1 回复  |  直到 15 年前
        1
  •  0
  •   Dave Markle    15 年前

    你说的用户ID是什么意思?

    因此,在实现AuthenticateRequest()时,可以获取HttpContext.Current.User.Identity.Name,并使用它从数据库中查找用户ID。从这里,您可以构造自己的IPrincipal派生对象,并将HttpContext.Currrent.User引用设置为您创建的对象。然后你可以在你的页面中把“User”转换成你创建的对象,并读取用户ID。下面是一些示例代码(它实际上缓存了主体对象,这样您就不必在每次请求时都访问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.");
            }
        }