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.