如何在SharePoint中查找已登录的用户?

14

我已经开发了一个“Web部件”,需要部署在Sharepoint服务器上。我需要在Web部件中获取登录Sharepoint服务器的用户用户名。

我该如何获取该用户名?

6个回答

29

以下方法对我有效:

SPWeb theSite = SPControl.GetContextWeb(Context);
SPUser theUser = theSite.CurrentUser;
string strUserName = theUser.LoginName;

并检查这个


10
更好的写法是:string strUserName = SPContext.Current.Web.CurrentUser.LoginName;该代码用于获取当前用户的登录名。 - iambriansreed

13

你可以使用:

SPWeb web = SPControl.GetContextWeb(this.Context);
string userName = web.CurrentUser.LoginName;
或者
string userName = this.Context.User.Identity.Name;

同时您还应该检查this.Context.User.Identity.IsAuthenticated以确保在尝试提取用户名之前有用户已登录。


我更喜欢第二个选项。对我来说,问题在于内部映射到AD时,它有一堆垃圾前缀,比如0#.w|domain\username。但除此之外,第二个实现对我非常有效。 - GoldBishop
@GoldBishop,您可以使用以下代码从声明表示中获取用户名:SPClaimProviderManager mgr = SPClaimProviderManager.Local; if (mgr != null) { userName = mgr.DecodeClaim(SPContext.Current.Web.CurrentUser.LoginName).Value; } - Mikael Svenson
有趣,我会进行一些测试,看看它如何解释。但除此之外,我只是做了 userid = this.Context.User.Identity.Name; userid = userid.Substring( userid.IndexOf( '|' ) + 1 ); 并且能够将垃圾与所需信息分离。 - GoldBishop
这个可以工作,但并非垃圾。它是一个索赔标识符。欢迎来到身份的新世界 :) - Mikael Svenson
取决于你的看法,对于我需要的信息来说它是垃圾。我知道这些信息很描述性,但这是我不需要的额外负担文本 ;) - GoldBishop

5

大家好,我找到了我的问题的答案,希望这对你们有用... 首先,在您的Web部件中添加对MicrosoftSharepoint.dll文件的引用。 然后编写 using Microsoft.SharePoint;

            string username;
            string sspURL = "URL where Sharepoint is deployed";

            SPSite site = new SPSite(sspURL);

            SPWeb web = site.OpenWeb();

            SPUser user = web.CurrentUser;

            username = user.LoginName;

            site.AllowUnsafeUpdates = true;

亲爱的,Jigar <3


3

SPContext.Current.Web.CurrentUser


1

您还可以通过_spPageContextInfo属性获取当前已登录用户的ID。

 _spPageContextInfo.userId

您可以通过_spPageContextInfo获取当前用户的ID。尝试这个可能会有帮助。


1

//别忘了添加 System.DirectoryServices.AccountManagement 的引用并使用 System.DirectoryServices.AccountManagement;

    PrincipalContext insPrincipalContext = new PrincipalContext(ContextType.Domain, "MyDomain","DC=MyDomain,DC=com");
    UserPrincipal insUserPrincipal = new UserPrincipal(insPrincipalContext);
    insUserPrincipal.Name = "*";
    PrincipalSearcher insPrincipalSearcher = new PrincipalSearcher();
    insPrincipalSearcher.QueryFilter = insUserPrincipal;
    PrincipalSearchResult<Principal> results = insPrincipalSearcher.FindAll();
    foreach (Principal p in results)
    {
        Console.WriteLine(p.Name);
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接