Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get bundling version token programmatically?

We are developing a Main WebApp with angularJS as a Single Page application for a Cordova mobile App.

We have moved part of the static resources into a couple of bundles that will be served from a different CDN WebApp from another domain.

We are not using the @Scripts.Render @Styles.Render razor helper because bundles are directly referenced from the embedded static index.html inside the mobile app like this (Appended via AngularJS):

<script src="https://service.foo.it/CDN/cdnFooJs"></script>
<script src="https://service.foo.it/CDN/cdnFooCss"></script>

As we are not using razor, we are not appending any cache token to the src and that's not what we want; we need a version token to force the client to download the updated version of the bundle.
I've read in some previous post that the v token is calculated every time Scripts.Render is used.

Now, the question is:
is it possible, to access the value of this token programmatically ?

We would like to create a service controller that, given a bundles route, returns the SHA256 token of the bundle.
Once received,it will be used to build the script tags that will be appended dinamically to the DOM.

<script src="https://service.foo.it/CDN/cdnFooJs?vtoken=asd3...."></script>
<script src="https://service.foo.it/CDN/cdnFooCss?vtoken=dasdasrq..."></script>

Note:
We already know that we can create our token by ourselves (for example using the build number), but it would nice to have something with less effort and more tied to the bundle mechanism.

like image 514
systempuntoout Avatar asked Sep 15 '14 10:09

systempuntoout


1 Answers

Here's a brief example of getting the v token from virtual bundle path.

public class BundleTokenController : ApiController
{
    public string Get(string path)
    {
        var url = System.Web.Optimization.Scripts.Url(path).ToString(); 
        //This will return relative url of the script bundle with querystring

        if (!url.Contains("?"))
        {
            url = System.Web.Optimization.Styles.Url(path).ToString(); 
            //If it's not a script bundle, check if it's a css bundle
        }

        if (!url.Contains("?"))
        {
            throw new Exception("Invalid path"); 
            //If neither, the path is invalid, 
            //or something going wrong with your bundle config, 
            //do error handling correspondingly
        }

        return GetTokenFromUrl(url);
    }

    private static string GetTokenFromUrl(string url)
    {
        //Just a raw way to extract the 'v' token from the relative url, 
        //there can be other ways

        var querystring = url.Split('?')[1];

        return HttpUtility.ParseQueryString(querystring)["v"];
    }
}
like image 143
tweray Avatar answered Oct 01 '22 19:10

tweray