Return Current User SharePoint MySite URL

Sometimes in code you want to include a link to the users MySite url in a string. This is helpful when doing things like writing out sets of user names in a WebPart, and want to include a link to more information regarding the user. You can accomplish this pretty easy by tapping into the SharePoint Object Model, and is a nice enhancement that adds a little bit of elegancy to a WebPart.

The first thing that you have to do is build a small test in order to determine whether the user has been authenticated to SharePoint. This can be done using the IsAuthenticated property against the user identity within the current site context, nothing real fancy here. This will be passed into the _curUser global variable (a private string) in the WebPart class.


SPWeb web = SPControl.GetContextWeb(this.Context);

if (this.Context.User.Identity.IsAuthenticated)
this._curUser = web.CurrentUser.LoginName;

Afterwords, you can loop through all the site collection using the sites property of the SPWebApplication class with a foreach loop. Following, using the SPWeb.WebTemplate property will get the name of the site definition that was used to create a relevant site. Since the SharePoint site definitions are explicitly named within the SharePoint 12 hive, you can test for the folder name of the MySite site definition by checking whether the return is equivalent to the string “SPSPERS” (the name of the MySite site definition). The if statement is extended in order to pass the current users login information to properly match it to the right user. Following, you can return the url of the user MySite by using the SPWeb.Url property.

foreach (SPSite site in webapp.Sites)
if (site.RootWeb.WebTemplate.ToUpper().StartsWith(“SPSPERS”) && site.Owner.LoginName.Equals(this._curUser))
return site.RootWeb.Url;


That’s all! Now you have a reference to the current user’s my site. You can decorate this within your rendered WebPart HTML stream by doing a similiar site definition test to do things like parse out an image to make your Webpart property by doing (web.WebTemplate.ToUpper().StartsWith(“SPSPERS”)).


5 thoughts on “Return Current User SharePoint MySite URL”

  1. ServerContext context = ServerContext.GetContext(site);

    UserProfileManager profileManager = new UserProfileManager(context);
    UserProfile profile = profileManager.GetUserProfile(HttpContext.Current.User.Identity.Name);
    string personUrl = profile.PersonalSite.Url;

  2. Do you know how to do this in client object model ?

    I can’t return the current user of an sharepoint 2013 autohosted app .
    the code always returns the administrator when i return the current user.

    Here is the code i’m using:

    ClientContext context = new ClientContext(“full url”);
    User user = context.Web.CurrentUser; //always returns “url/Administrator”

Leave a Reply

Your email address will not be published. Required fields are marked *