How to find the logged in user in Sharepoint?

2019-02-04 14:56发布

I have developed a "web part" that has to be deployed on a Sharepoint server. I need the username of the user, who has logged in the sharepoint server within the web part.

How do I get that username?

6条回答
霸刀☆藐视天下
2楼-- · 2019-02-04 15:18

Following worked for me:

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

and check this out.

查看更多
迷人小祖宗
3楼-- · 2019-02-04 15:20

//don't forget to add System.DirectoryServices.AccountManagement as reference and using 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);
    }
查看更多
Ridiculous、
4楼-- · 2019-02-04 15:29

You can use:

SPWeb web = SPControl.GetContextWeb(this.Context);
string userName = web.CurrentUser.LoginName;

or

string userName = this.Context.User.Identity.Name;

And you should check this.Context.User.Identity.IsAuthenticated as well to ensure there is a user logged in before trying to extract the username.

查看更多
孤傲高冷的网名
5楼-- · 2019-02-04 15:29

You can also get current logged user ID by _spPageContextInfo property.

 _spPageContextInfo.userId

You will get current user's ID by _spPageContextInfo. Try this may help you.

查看更多
成全新的幸福
6楼-- · 2019-02-04 15:34

SPContext.Current.Web.CurrentUser

查看更多
Evening l夕情丶
7楼-- · 2019-02-04 15:36

Hey all, i got the answer for my question Hope this will work for you all... First add a reference to the MicrosoftSharepoint.dll file in your web part. then write 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;

Yours, Jigar <3

查看更多
登录 后发表回答