【问题标题】:Is there any way to get the requesting user's ID in an ASP.NET web service method?有没有办法在 ASP.NET Web 服务方法中获取请求用户的 ID?
【发布时间】:2023-03-04 03:22:01
【问题描述】:

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

【问题讨论】:

  • 您的网络服务是否设置了匿名禁用和 Windows 集成安全性?
  • 你说的是ASMX Web Service、WCF Web Service还是AJAX调用的ASP.NET Page Method?
  • @Justin - ASMX,抱歉,应该这么说,以为“ASP.NET Web 服务”暗示了这一点。 @Otavio,我认为你正中了它的头。

标签: asp.net soap


【解决方案1】:

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

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

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

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

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.");
        }
    }

【讨论】:

    猜你喜欢
    • 2018-02-02
    • 1970-01-01
    • 2016-09-17
    • 2011-02-04
    • 2022-10-25
    • 1970-01-01
    • 1970-01-01
    • 2020-09-20
    • 2021-06-04
    相关资源
    最近更新 更多