【问题标题】:Get MVC Bundle Querystring获取 MVC 包查询字符串
【发布时间】:2015-07-21 13:15:54
【问题描述】:

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

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

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

是否可以提取v查询字符串?:

4Z9jKRKGzlz-D5dJi5VZtpy4QJep62o6A-xNjSBmKwU1


我尝试在捆绑转换中执行此操作,但没有运气。我发现即使将UseServerCache 设置为false,转换代码也并不总是运行。

【问题讨论】:

  • 好奇你为什么想要它?
  • @DavidG 我有一个服务器场,想检查当前服务器是否有正确的文件,以便较新的缓存破坏器不会缓存旧内容。相关:stackoverflow.com/questions/31535879/…
  • 您可以使用Styles.Render("~/blah.css") 获取<link... 作为字符串,然后从那里提取值。
  • @DavidG 这将获得该服务器生成的内容。缓存中的版本可能与场中另一台服务器的应用程序的较新/较旧版本不同。我计划将您提到的值与请求中的值进行比较,以确保它们匹配:)
  • 这是一个XY Problem。你相信 Y 会解决某个问题 X,但你还没有描述 X。什么问题 (X) 得到 v 的值去解决 (Y)?

标签: c# asp.net asp.net-mvc query-string bundling-and-minification


【解决方案1】:

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

要解决这个问题,您需要在System.Web.Optimization namespace 中进行探索。

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


更新

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

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

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

  3. 从 bundler 中获取 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);

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

希望这会有所帮助!祝你好运!

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

【讨论】:

  • 谢谢 Frison,我认为您对 GetContentHashCode() 的私密性是正确的,我之前遇到过 - forums.asp.net/t/…
  • 如果您有机会找到其他方法,请告诉我!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-08
  • 1970-01-01
  • 2013-07-29
  • 1970-01-01
  • 2011-07-23
  • 1970-01-01
相关资源
最近更新 更多