Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is there a way to get the hash from a path? #87

Open
johnnyoshika opened this issue Jun 1, 2018 · 3 comments
Open

Is there a way to get the hash from a path? #87

johnnyoshika opened this issue Jun 1, 2018 · 3 comments

Comments

@johnnyoshika
Copy link

Given a path to a static asset (e.g. /js/foo.js), is there a way to get the hash (i.e. version / cache buster) of that file? The reason why I ask is that I have a special tag helper that lazy-loads scripts and I'd like to append the hash to the file path without using the WebOptimizer tag helper.

Great library, BTW!

@serkanyazicioglu
Copy link

@johnnyoshika could you find a solution for this? I'm stuck with the same issue right now. Thx...

@serkanyazicioglu
Copy link

serkanyazicioglu commented Jul 15, 2021

Developed an extension for this, if anybody needs.

public static class PageExtensions
    {
        public static string AddBundleVersionToPath(this IRazorPage page, string path)
        {
            var context = page.ViewContext.HttpContext;
            var assetPipeline = context.RequestServices.GetService<WebOptimizer.IAssetPipeline>();

            if (assetPipeline.TryGetAssetFromRoute(path, out IAsset asset))
            {
                return string.Concat(path, "?v=", asset.GenerateCacheKey(context));
            }
            else
            {
                return path;
            }
        }
}

You should add your extension namespace to _ViewImports.cshtml. Then method can be used on any page.

_ViewImports.cshtml
@using Your.Extensions.Namespace

your.cshtml

var element = document.createElement("script");
element.src = "@this.AddBundleVersionToPath("/bundle-path.min.js")";

@madskristensen maybe this can be documented?

@christopherpickering
Copy link

@serkanyazicioglu Thanks for posting this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants