SharePointContext null in postback

If you are experiencing issues with the SharePointContext class returning NULL when you call SharePointContextProvider.Current.GetSharePointContext(HttpContext) in a postback you may what to check that the context is initialized on the first page load. This can be done for example by calling GetSharePointContext in Page Load event or SharePointContextProvider.CheckRedirectionStatus in Page PreInit.

The reason for this is that the SharePointContext class is dependent on parameters (AppContext, AppContextToken, AccessToken and SPAppToken) being in the request as form or querystring parameters. If present SharePointContext will store values in session and cookie for use in future postbacks. Therefor if SharePointContext is not used at all on initial load all dependent parameters will get lost in postback.

It’s pretty easy to reproduce this, just create a new provider-hosted app using the ASP.NET MVC Form Application template. Remove any code in Page_PreInit and move the example code in Page_Load to a button click event that fires on postback. Debug application and notice that GetSharePointContext(HttpContext) returns NULL in button click event.

One Response to “SharePointContext null in postback”

  1. Melvin Says:

    Did you manage to solve this?

Leave a Reply">Entries (RSS) and Comments (RSS).