Unable to Follow Content Programmatically

Developers have reported that after applying the October 2015 CU, they are unable to follow content programmatically using SPSocialFollowingManager.Follow method. While reported for the October CU, the change appears to be from the September 2015 CU, thanks to an improved hybrid User Profile experience.

The September 2015 CU added the option to follow on-premises Sites and have the followed Sites appear in the user’s SharePoint Online user profile. This is a great feature, but unfortunately broke the SPSocialFollowingManager.Follow functionality.

What has broken this functionality is Microsoft.Office.Server.UserProfiles.FollowedContent.RefreshFollowedItem(FollowedItem item, SPS2SAppExecutionPolicy policy). This method now contains the line item2.IsHybrid = this.Profile.IsFollowingHybridSetting() && (FollowedItemType.Site == item2.ItemType);. The IsFollowingHybridSetting() method is calling UserProfileServiceApplicationProxy.GetProxy(SPServiceContext.Current), however SPServiceContext is null. Because the service context is null, adding the followed item fails with the error:

FollowedContent.RefreshFollowedItem(item.Url=http://spwebapp1/, policy=Allow) : Local execution failed; Could not refresh followed item http://spwebapp1/: Exception: Value cannot be null.  Parameter name: serviceContext

That said, there’s a workaround! What needs to be done is to properly set HttpContext.Current. If, within the scope of your custom code, HttpContext.Current is set (even through a console application), SPServiceContext will not be null and an item can be followed.

Trevor Seward is a Microsoft Office Apps and Services MVP who specializes in SharePoint Server administration, hybrid scenarios, and SharePoint Online. He has been working with SharePoint for 16 years from SharePoint 2003 on up, managing environments with terabytes of content for 150,000+ user organizations. Trevor is an author of Deploying SharePoint 2016 and Deploying SharePoint 2019. You can find him on Twitter and in /r/sharepoint.