6

I am building a web part to put on Sharepoint My Sites. I need to get the SPUser whose My Site the web part is on. Currently I simply use

Request.QueryString["accountname"]

but this will not work on my own My Site, and I am not sure it will work all the time either.

Nacht
  • 3,342
  • 4
  • 26
  • 41

3 Answers3

2

here is another approach using UserProfile (Microsoft.Office.Server.UserProfiles)

var profileLoader =   Microsoft.SharePoint.Portal.WebControls.ProfilePropertyLoader.FindLoader(HttpContext.Current.Handler as Page);
var userProfile = profileLoader.ProfileLoaded;

var loginName = userProfile["AccountName"];

And then just get your SPUser from SPContext.Current.Web;

luccio
  • 485
  • 1
  • 6
  • 24
  • hmm.... interesting... is this guaranteed to work every time? it looks like it may only work on the home page of a my site – Nacht Mar 11 '13 at 22:20
2

When Request.QueryString["accountname"] is empty the user should be on its own mysite so then you could look in SPContext.Current.Web.CurrentUser to get the user.

Daniel
  • 3,741
  • 1
  • 16
  • 21
  • 2
    yes, but don't forget that the CurrentUser property returns the currently logged in user, not the user on whom's MySite you are. I guess getting the accountname from the query string will be your only option – int32 Oct 12 '11 at 08:13
  • As Nacht writes in his post there is no accountname query string when you are on your own MySite so you need to account for both cases in the code: When on somebody else MySite use the querystring and when on the currents users MySite the querystring is empty so then look in the SPContext for the logged on user. – Daniel Oct 12 '11 at 09:12
  • Using the web request seems like a hack, but if it's my only option, it's my only option. Thank you! – Nacht Oct 12 '11 at 22:34
1

Another possible way of doing this is to use the SPSite's Owner property. This will give you an SPUser object which is usually preferable. This property correlates to the "Site Owner" property which can be configured in Central Admin under "Change Site Collection Administrator". However be aware that since this can be configured, it is not to be trusted as an absolute source of knowing whose my site you're on.

Nacht
  • 3,342
  • 4
  • 26
  • 41
  • This also may throws 403 Forbidden when users have access to a subweb but no Personal Site root, like in Blog. – Luizgrs Aug 15 '16 at 15:05