Making SharePoint App Access Token Caching work in MVC

I’ve put together a couple of SharePoint Apps that use MVC to run the remote web application.  When you use MVC for a SharePoint remote web, Visual Studio automatically includes some helpful files to help manage the SharePoint access token.  I decided to go ahead and try to use these files to help me out, but I ran into an issue… they don’t work.  At least not right off.

After digging around for a bit, I noticed that the access caching mechanism was working fine.  But there is a JavaScript file named spcontext.js that you have to include that automatically rewrites URLs to append the SPHostUrl value that the caching mechanism uses to retrieve the access token. I included the file, but none of my URLs were being rewritten.  The culprit appears to be the following line of code:

if (queryString[0] === "?") {
     queryString = queryString.substring(1);
}

This is checking to see if the first character of the query string is a ? and if so, it strips it off.  The problem is that queryString[0] always returns null and does not return the first character of the string.  This left the ? character in place which messed up the query string parser.  I went in and updated the code to use the charAt function instead:

if (queryString.charAt(0) === "?") {
     queryString = queryString.substring(1);
}

And with that change in place, my URLs were being rewritten to automatically append the SPHostUrl parameter, and then I could navigate around my MVC application while retaining the key to the cached access token.