繁体   English   中英

获取MVC捆绑查询字符串

[英]Get MVC Bundle Querystring

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

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

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

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

4Z9jKRKGzlz-D5dJi5VZtpy4QJep62o6A-xNjSBmKwU1


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

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

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

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


更新资料

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

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

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

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

  4. 对微软的不良设计感到生气

让我们继续讲#2(请注意,由于它被标记为内部API,而不是公共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的内部部件发生变化,则测试将失败,您将知道问题出在哪里。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM