javascript - VS 2012 中的 HTTP 处理程序和 javascript 捆绑

标签 javascript asp.net localization httphandler bundling-and-minification

我目前正在尝试设置一个项目来实现 javascript 文件的本地化(如 here 所述),但同时我想在项目中捆绑和缩小 javascript。我遵循了有关捆绑和缩小的教程 here

我已经能够让两者分开工作,但是当我试图让它们一起工作时,我无法让本地化正常工作。我认为这是因为捆绑为它生成的捆绑/缩小的 javascript 创建了它自己的路由处理,所以我在 webconfig 中定义的 httpHandler 被忽略了。我不断收到 javascript 错误,提示“CustomTranslate is not defined”。

我尝试这样做是因为我们正在使用 ExtJS 构建许多控件,但我们需要能够对这些控件应用本地化。任何关于如何让他们一起工作的帮助/想法都将不胜感激。

使用 MVC,而是在 Visual Studio 2012 的 asp.net 中执行此操作。

这是我的代码:

BundleConfig.cs

namespace TranslationTest
{
    public class BundleConfig
    {
        public static void RegisterBundles(BundleCollection bundles)
        {
            //default bundles addeed here...

            bundles.Add(new ScriptBundle("~/bundles/ExtJS.axd").Include("~/Scripts/ExtJS/ext-all.js", "~/Scripts/ExtJS/TestForm.js"));

        }
    }
}    

网络配置:

<globalization uiCulture="auto" />
<httpHandlers>
  <add verb="*" path="/bundles/ExtJS.axd" type="TranslationTest.ScriptTranslator, TranslationTest" />
</httpHandlers>

Default.aspx

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TranslationTest._Default" %>

<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
    <script src="/bundles/ExtJS.axd"></script>
</asp:Content>    

测试表单.js:

Ext.require([
       'Ext.form.*',
       'Ext.layout.container.Column',
       'Ext.tab.Panel'
]);

Ext.onReady(function () {

    Ext.QuickTips.init();

    var bd = Ext.getBody();

    bd.createChild({ tag: 'h2', html: 'Form 1' });


    var simple = Ext.create('Ext.form.Panel', {
        url: 'save-form.php',
        frame: true,
        title: 'Simple Form',
        bodyStyle: 'padding:5px 5px 0',
        width: 350,
        fieldDefaults: {
            msgTarget: 'side',
            labelWidth: 75
        },
        defaultType: 'textfield',
        defaults: {
            anchor: '100%'
        },

        items: [{
            fieldLabel: CustomTranslate(FirstName),
            name: 'first',
            allowBlank: false
        }, {
            fieldLabel: CustomTranslate(LastName),
            name: 'last'
        }, {
            fieldLabel: CustomTranslate(Company),
            name: 'company'
        }, {
            fieldLabel: CustomTranslate(Email),
            name: 'email',
            vtype: 'email'
        }, {
            xtype: 'timefield',
            fieldLabel: CustomTranslate(Time),
            name: 'time',
            minValue: '8:00am',
            maxValue: '6:00pm'
        }],

        buttons: [{
            text: CustomTranslate(Save)
        }, {
            text: CustomTranslate(Cancel)
        }]
    });

    simple.render(document.body);


});

目前 FirstName、LastName 等都存储在资源文件中,如上面的链接示例所示。

脚本翻译器.cs

namespace TranslationTest
{
    public class ScriptTranslator : IHttpHandler
    {
        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(HttpContext context)
        {
            string relativePath = context.Request.AppRelativeCurrentExecutionFilePath.Replace(".axd", string.Empty);
            string absolutePath = context.Server.MapPath(relativePath);
            string script = ReadFile(absolutePath);
            string translated = TranslateScript(script);

            context.Response.Write(translated);

            Compress(context);
            SetHeadersAndCache(absolutePath, context);
        }

        #endregion

        private void SetHeadersAndCache(string file, HttpContext context)
        {
            context.Response.AddFileDependency(file);
            context.Response.Cache.VaryByHeaders["Accept-Language"] = true;
            context.Response.Cache.VaryByHeaders["Accept-Encoding"] = true;
            context.Response.Cache.SetLastModifiedFromFileDependencies();
            context.Response.Cache.SetExpires(DateTime.Now.AddDays(7));
            context.Response.Cache.SetValidUntilExpires(true);
            context.Response.Cache.SetCacheability(HttpCacheability.Public);
        }

        #region Localization

        private static Regex REGEX = new Regex(@"CustomTranslate\(([^\))]*)\)", RegexOptions.Singleline | RegexOptions.Compiled);

        private string TranslateScript(string text)
        {
            MatchCollection matches = REGEX.Matches(text);
            ResourceManager manager = new ResourceManager(typeof(TranslationTest.App_GlobalResources.text));

            foreach (Match match in matches)
            {
                object obj = manager.GetObject(match.Groups[1].Value);
                if (obj != null)
                {
                    text = text.Replace(match.Value, CleanText(obj.ToString()));
                }
            }
            return text;
        }

        private static string CleanText(string text)
        {
            text = text.Replace("'", "\\'");
            text = text.Replace("\\", "\\\\");
            return text;
        }

        private static string ReadFile(string absolutePath)
        {
            if (File.Exists(absolutePath))
            {
                using (StreamReader reader = new StreamReader(absolutePath))
                {
                    return reader.ReadToEnd();
                }
            }
            return null;
        }

        #endregion

        #region Compression

        private const string GZIP = "gzip";
        private const string DEFLATE = "deflate";

        private static void Compress(HttpContext context)
        {
            if (IsEncodingAccepted(DEFLATE, context))
            {
                context.Response.Filter = new DeflateStream(context.Response.Filter, CompressionMode.Compress);
                SetEncoding(DEFLATE, context);
            }
            else if (IsEncodingAccepted(GZIP, context))
            {
                context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
                SetEncoding(GZIP, context);
            }
        }

        private static bool IsEncodingAccepted(string encoding, HttpContext context)
        {
            return context.Request.Headers["Accept-encoding"] != null && context.Request.Headers["Accept-encoding"].Contains(encoding);
        }

        private static void SetEncoding(string encoding, HttpContext context)
        {
            context.Response.AppendHeader("Content-encoding", encoding);
        }

        #endregion

    }
}

全局.asax.cs

namespace TranslationTest
{
    public class Global : HttpApplication
    {
        void Application_Start(object sender, EventArgs e)
        {
            Microsoft.Web.Optimization.BundleTable.Bundles.EnableDefaultBundles();

            BundleConfig.RegisterBundles(System.Web.Optimization.BundleTable.Bundles);
            AuthConfig.RegisterOpenAuth();
        }
    }
}

我希望我已经涵盖了所有内容,但如果有任何遗漏,请告诉我。提前致谢!!

最佳答案

好的,我已经在您的示例中设置了所有内容并且可以正常工作,但是您需要使用 IBundleTransform 接口(interface)。我所做的一切细节都发布在下面..

我必须创建一个类来处理包转换(即翻译),而不是允许默认行为。

public class JsLocalizationTransform : IBundleTransform
    {
        public JsLocalizationTransform(){}

        #region IBundleTransform Members

        public void Process(BundleContext context, BundleResponse response)
        {
            string translated = TranslateScript(response.Content);

            response.Content = translated;
        }

        #endregion

        #region Localization

        private static Regex REGEX = new Regex(@"CustomTranslate\(([^\))]*)\)", RegexOptions.Singleline | RegexOptions.Compiled);

        private string TranslateScript(string text)
        {
            MatchCollection matches = REGEX.Matches(text);
            ResourceManager manager = new ResourceManager(typeof(TranslationTest.App_GlobalResources.text));

            foreach (Match match in matches)
            {
                object obj = manager.GetObject(match.Groups[1].Value);
                if (obj != null)
                {
                    text = text.Replace(match.Value, CleanText(obj.ToString()));
                }
            }

            return text;
        }

        private static string CleanText(string text)
        {
            //text = text.Replace("'", "\\'");
            text = text.Replace("\\", "\\\\");

            return text;
        }
        #endregion

    }

然后在 BundleConfig.RegisterBundles 方法中,您需要像这样创建和添加包:

var extjsBundle = new Bundle("~/bundles/ExtJS").Include("~/Scripts/ExtJS/ext-all.js", "~/Scripts/ExtJS/TestForm.js");
    extjsBundle.Transforms.Clear();
    extjsBundle.Transforms.Add(new JsLocalizationTransform());
    extjsBundle.Transforms.Add(new JsMinify());
    bundles.Add(extjsBundle);

然后我可以从 web.config 中删除 HttpHandler,因为它是通过 bundler 自动配置的。我还必须对 global.asax.cs 中的 Application_Start 方法进行一些更改

void Application_Start(object sender, EventArgs e)
        {
            //Microsoft.Web.Optimization.BundleTable.Bundles.EnableDefaultBundles(); 
            BundleTable.EnableOptimizations = true; //Added this line..
            BundleConfig.RegisterBundles(System.Web.Optimization.BundleTable.Bundles);
            AuthConfig.RegisterOpenAuth();
        }

因为 JSLocalisationTransform 类正在处理包转换和翻译,所以我完全删除了 ScriptTranslator 类。

希望对您有所帮助。

关于javascript - VS 2012 中的 HTTP 处理程序和 javascript 捆绑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17144914/

相关文章:

c# - ASP.Net:在共享/静态函数中使用 System.Web.UI.Control.ResolveUrl()

c# - C# 中的本地化属性参数

c# - 每个表单/其他字符串仅使用 1 个资源文件而不是 1 个资源文件

javascript - 以编程方式触发点击处理程序

访问 "attribute"时 JavaScript 对象值未定义?

c# - 创建虚拟目录失败,错误 : redirection. 配置

c# - 如何在按钮单击事件上打开新的浏览器窗口?

ios - 从 Objective-C 中的货币代码获取货币符号

javascript - 原始 javascript 打印项目从 json 对象到列表中的屏幕

javascript - 更新子可观察对象时,Knockout js css 似乎不会重新计算