获取 MVC 捆绑包查询字符串

2023-11-22

是否可以在 ASP.NET MVC 中检测捆绑查询字符串?

例如,如果我有以下捆绑请求:

/css/bundles/mybundle.css?v=4Z9jKRKGzlz-D5dJi5VZtpy4QJep62o6A-xNjSBmKwU1

是否可以提取v请求参数?:

4Z9jKRKGzlz-D5dJi5VZtpy4QJep62o6A-xNjSBmKwU1


我尝试过在捆绑变换中执行此操作,但没有运气。我发现即使有UseServerCache set to false转换代码并不总是运行。


我已经有一段时间没有使用 ASP Bundler 了(我记得它很糟糕),这些笔记来自我的记忆。请验证它是否仍然有效。 希望这将为您的搜索提供一个起点。

为了解决这个问题,你需要探索System.Web.Optimization namespace.

最重要的是System.Web.Optimization.BundleResponse类,它有一个名为GetContentHashCode()这正是你想要的。不幸的是,MVC Bundler 的架构很糟糕,我敢打赌这仍然是一种内部方法。这意味着您将无法从代码中调用它。


Update

感谢您的验证。所以看来您有几种方法可以实现您的目标:

  1. 使用与 ASP Bundler 相同的算法自行计算哈希值

  2. 使用反射调用Bundler的内部方法

  3. 从捆绑器获取 URL(我相信有一个公共方法)并提取查询字符串,然后从中提取哈希(使用任何字符串提取方法)

  4. 对微软糟糕的设计感到愤怒

让我们选择#2(小心,因为它被标记为内部的而不是公共 API 的一部分,Bundler 团队对该方法的重命名会破坏事情)

//This is the url passed to bundle definition in BundleConfig.cs
string bundlePath = "~/bundles/jquery";
//Need the context to generate response
var bundleContext = new BundleContext(new HttpContextWrapper(HttpContext.Current), BundleTable.Bundles, bundlePath);

//Bundle class has the method we need to get a BundleResponse
Bundle bundle = BundleTable.Bundles.GetBundleFor(bundlePath);
var bundleResponse = bundle.GenerateBundleResponse(bundleContext);

//BundleResponse has the method we need to call, but its marked as
//internal and therefor is not available for public consumption.
//To bypass this, reflect on it and manually invoke the method
var bundleReflection = bundleResponse.GetType();

var method = bundleReflection.GetMethod("GetContentHashCode", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

//contentHash is whats appended to your url (url?###-###...)
var contentHash = method.Invoke(bundleResponse, null);

The bundlePath变量与您为包指定的名称相同(来自BundleConfig.cs)

希望这可以帮助!祝你好运!

编辑:忘了说围绕这个添加一个测试是个好主意。该测试将检查是否存在GetHashCode功能。这样,将来如果 Bundler 的内部发生变化,测试就会失败,您就会知道问题出在哪里。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

获取 MVC 捆绑包查询字符串 的相关文章

随机推荐