ASP.NET Mono MVC 4 应用程序使用 MVC4 内置的 CSS 和 js 文件捆绑和缩小功能。
如果使用fiddler将请求中的用户代理字符串更改为Eureka/1
User-Agent: Eureka/1
重新发出请求,将包含所有注释的整个源代码发送给客户端。
如何防止这种情况,使源代码中的注释无法被客户端检查?
来源:http://www.codeproject.com/Articles/728146/ASP-NET-MVC-bundles-internals
我尝试将 debug='false'
添加到 web.config
但问题仍然存在。
最佳答案
我能够通过创建继承自 IBundleBuilder
的类来删除注释。 。这是为 Microsoft ASP.NET Web Optimization Framework 1.1.3 写的更新于 2014 年 2 月 20 日:
public class ScriptBundleBuilder : IBundleBuilder
{
public virtual string BuildBundleContent(Bundle bundle, BundleContext context, IEnumerable<BundleFile> files)
{
var content = new StringBuilder();
foreach (var file in files)
{
FileInfo f = new FileInfo(HttpContext.Current.Server.MapPath(file.VirtualFile.VirtualPath));
Microsoft.Ajax.Utilities.CodeSettings settings = new Microsoft.Ajax.Utilities.CodeSettings();
settings.RemoveUnneededCode = true;
settings.StripDebugStatements = true;
settings.PreserveImportantComments = false;
settings.TermSemicolons = true;
var minifier = new Microsoft.Ajax.Utilities.Minifier();
content.Append(minifier.MinifyJavaScript(Read(f), settings));
}
return content.ToString();
}
private string Read(FileInfo file)
{
using (var r = file.OpenText())
{
return r.ReadToEnd();
}
}
}
public class StyleBundleBuilder : IBundleBuilder
{
public virtual string BuildBundleContent(Bundle bundle, BundleContext context, IEnumerable<BundleFile> files)
{
var content = new StringBuilder();
foreach (var file in files)
{
FileInfo f = new FileInfo(HttpContext.Current.Server.MapPath(file.VirtualFile.VirtualPath));
Microsoft.Ajax.Utilities.CssSettings settings = new Microsoft.Ajax.Utilities.CssSettings();
settings.CommentMode = Microsoft.Ajax.Utilities.CssComment.None;
var minifier = new Microsoft.Ajax.Utilities.Minifier();
content.Append(minifier.MinifyStyleSheet(Read(f), settings));
}
return content.ToString();
}
private string Read(FileInfo file)
{
using (var r = file.OpenText())
{
return r.ReadToEnd();
}
}
}
然后告诉包使用这个构建器。此示例适用于 StyleBundle:
public static void RegisterBundles(BundleCollection bundles)
{
var bundle = new StyleBundle("~/Content/themes/base/css");
bundle.Builder = new StyleBundleBuilder();
bundle.Include("~/Content/themes/base/jquery.ui.core.css",
"~/Content/themes/base/jquery.ui.resizable.css",
//etc
);
bundles.Add(bundle);
var scriptBundle = new ScriptBundle("~/bundles/modernizr");
scriptBundle.Builder = new ScriptBundleBuilder();
scriptBundle.Include("~/Scripts/modernizr-*");
bundles.Add(scriptBundle);
BundleTable.EnableOptimizations = true; //for testing
}
这已在 Chrome 中通过将用户代理更改为 Eureka/1.0
进行测试/确认。 .
至少对于 Web 优化框架的某些早期版本(我认为是 1.0 及之前版本),唯一的区别是最终参数。所以它看起来像 public virtual string BuildBundleContent(Bundle bundle, BundleContext context, IEnumerable<FileInfo> files)
并且只需要进行微小的更改即可工作...尽管您可能最好只是更新。
关于这个问题,有人提出了in another recent SO post关于在缩小过程中如何删除许可信息...我做了 a NuGet Package来解决这些问题。
关于asp.net - 如何防止用户代理: Eureka/1 to return source code,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21991736/