Tuesday, April 07, 2009

Accessing Current User in MOSS

You could get the current user in SharePoint by calling the following code:

SPUser user = SPContext.Current.Web.CurrentUser;

But to access the current user inside the code running under Elevated Privileges, open new reference to SPSite.

SPSecurity.RunWithElevatedPrivileges(delegate()

{
    using (SPSite site = new SPSite(“http:\\MOSS_SITE”))

{
      using (SPWeb web = site.OpenWeb())

          SPUser user =SPContext.Current.Web.CurrentUser;

    }

}
);

The above code will switch the user context and now, you would get the user under which application pool is running

1 comments:

IGD said...

Hi Sanjay, I am having problems getting the current user the way you suggest above. The code I want to run as the host app pool's identity is inside a workflow code activity. This is what I have:

SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite("http://servername"))
{
using (SPWeb web = site.OpenWeb())
{
SPUser currentUser = SPContext.Current.Web.CurrentUser;

try
{
SuperType.CRM_WS_URL = "http://crmserver/mscrmservices/2007/crmservice.asmx";
//SuperType.srvc.Credentials = new System.Net.NetworkCredential("username", "password", "domain");

SuperContact test_contact = new SuperContact(_FirstName, _LastName);

test_contact.Publish(null);
}
catch (SoapException ex)
{
Console.WriteLine("Soap Error!!!!!!!!" + ex.Detail.InnerText);
}
}
}
}
);

When I debug the workflow, CurrentUser is null because SPContext is null! I then tried getting the CurrentUser from the web object and it is Sharepoint\System! Nightmare, as I am trying to insert into CRM but Sharepoint\System doesn't have privileges...but the host app pool's identity does, I have triple checked. Any help here? Thanks!