Web Parts: Get Current User with Impersonation


Here is some code that I find myself using in all of my web parts.  You are also free to use it.  I simply reuse it in all of my web parts.

It returns “DOMAIN\\USERNAME”

 

private string GetUserAccount()
{
    // Normally used with all web parts
    // By: Bill Daugherty II
    // Date Modified: 08/15/2010

    string impersonate = string.Empty;
    try
    {
        if (Request.QueryString["impersonate"].Length > 0) impersonate = Request.QueryString["impersonate"];
        if (Request.QueryString["i"].Length > 0) impersonate = Request.QueryString["i"];
    }
    catch
    {

    }
    string staffMember = string.Empty;

    // Gets the staff SAM account
    SPSite site = SPContext.Current.Site;

    SPServiceContext context = SPServiceContext.GetContext(site);

    // Uses the profile manager that was set up in Central Admin
    UserProfileManager profileManager = new UserProfileManager(context);

    if (impersonate.Length == 0)
    {
        // staffMember = SPContext.Current.Web.CurrentUser.LoginName.ToString();
        staffMember = HttpContext.Current.Request.ServerVariables["AUTH_USER"];
    }
    else
    {
        staffMember = impersonate;
    }

    return staffMember;

}

If you find that you use this also, please just add a comment.

Bill

Categories: SharePoint or Custom Development | 1 Comment

Post navigation

One thought on “Web Parts: Get Current User with Impersonation

  1. Brett

    I am having trouble getting in all the namespaces to support this class. So far I have:
    using System;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using Microsoft.SharePoint;
    using Microsoft.Office.Server;

    What am I missing? Thanks!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Blog at WordPress.com. Theme: Customized Adventure Journal by Contexture International.

Follow

Get every new post delivered to your Inbox.