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);

//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;

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

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: https://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spcontext.aspx

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two-decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. He has held various positions including SharePoint Architect, Administrator, Developer and consultant, has helped many organizations to implement and optimize SharePoint solutions. Known for his deep technical expertise, He's passionate about sharing the knowledge and insights to help others, through the real-world articles!

One thought on “What is SPContext in SharePoint?

  • Hey, can i get SPContext in Powershell


Leave a Reply

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