What is SPContext in SharePoint?

SPContext is often used with custom web parts and pages to retrieve SharePoint site objects from the context of the SharePoint site accessed. Its a good practice to use SPContext instead of creating new objects (So that we can avoid disposal of objects). SPContext object will be available for access in our coding as long as the current HttpContext is not null. Meaning, if a user is logged in to a SharePoint site, the SPContext object will always be available.

Using SPContext we can access many objects like SPWeb. There are other objects you can access using SPContext:

  • SPSite
  • SPList
  • SPListItem
  • SPFile
  • SPFIeldCollection
  • SPItem
  • SiteFeatures, etc

Here is an example of getting the current site URL and user name:

string currentWeb = "Current Site URL:" +SPContext.Current.Site.Url;
string currentUser = "Current User Name:"+ SPContext.Current.Web.CurrentUser.Name;
LiteralControl lblCurrentUser = new LiteralControl(currentWeb +"<br/>" + currentUser);
Controls.Add(lblCurrentUser);

//Add new List item
SPList oSPList = SPContext.Current.Web.Lists["Tracking List"];
SPContext.Current.Web.AllowUnsafeUpdates = true;

SPListItem oSPListItem= oSPList.Items.Add();
oSPListItem["Title"] = "Created by " + currentUser;
oSPListItem.Update();

//Another example Using SPWeb             
SPContext.Current.Web.Properties["SMTPServer"] = "smtp.company.com";
SPContext.Current.Web.Properties.Update();
SPContext.Current.Web.Update(); 

SPContext.Current.Web.AllowUnsafeUpdates = false;

In the same way, for event handlers, you can use, e.g. SPSite site = properties.Feature.Parent as SPSite;

SPContext is available in Sandboxed solutions also.

MSDN Reference: http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spcontext.aspx

Salaudeen Rajack

Salaudeen Rajack is a SharePoint Architect with Two decades of SharePoint Experience. He loves sharing his knowledge and experiences with the SharePoint community, through his real-world articles!

One thought on “What is SPContext in SharePoint?

  • August 6, 2015 at 8:58 PM

    Hey, can i get SPContext in Powershell

    Reply

Leave a Reply