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:
- 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: https://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spcontext.aspx
One thought on “What is SPContext in SharePoint?”
Hey, can i get SPContext in Powershell