c# - 获取 MVC 包查询字符串

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

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

例如,如果我有以下 bundle 请求:

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

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

4Z9jKRKGzlz-D5dJi5VZtpy4QJep62o6A-xNjSBmKwU1


我试过在捆绑转换中这样做,但没有成功。我发现即使将 UseServerCache 设置为 false,转换代码也不总是运行。

最佳答案

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

要解决这个问题,您需要在 System.Web.Optimization 命名空间 中探索。

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


更新

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

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

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

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

  4. 因糟糕的设计而对微软生气

让我们继续 #2(小心,因为它被标记为内部而不是公共(public) 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 变量与您为 bundle 指定的名称相同(来自 BundleConfig.cs)

希望对您有所帮助!祝你好运!

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

关于c# - 获取 MVC 包查询字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31540121/

相关文章:

asp.net-mvc - URL 路由 捕获所有

c# - 避免输入参数出现 "null entry for parameter id of non-nullable type"错误的干净方法

C#清除已关闭应用程序的托盘图标

c# - 向网站添加静态子域的推荐方法是什么?

c# - WCF REST 服务的 Azure 缓存间歇性响应时间

javascript - 为什么我的 blazor.server.js 之后无法加载任何 js?

c# - monotouch.dialog styledstringelement调整单元格宽度

c# - 在 .NET 中传递事件

javascript - 在 JavaScript 中调用 WebService

javascript - 访问 Javascript block 内的页面模型