ExpressionBuilder的常见说明见https://msdn.microsoft.com/zh-cn/library/System.Web.Compilation.ExpressionBuilder(v=vs.80).aspx
下面贴代码:
编写自定义ExpressionBuilder用于翻译,翻译文件缓存依赖。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; using System.Web.Compilation; using System.Web.UI; using System.CodeDom; using System.Web.Hosting; using System.Web.Caching; using System.Xml; namespace ExpressionBuilderTest.Library { /// <summary> /// 自定义ExpressionBuilder /// </summary> public class SPExpressionBuilder:ExpressionBuilder { // Create a method that will return the result // set for the expression argument. public static object GetEvalData(string expression, Type target, string entry) { XmlDocument doc = (XmlDocument)HostingEnvironment.Cache["transDoc"]; if (doc == null) { doc = new XmlDocument(); string filePath = HostingEnvironment.MapPath("~/Translate.config"); doc.Load(filePath); CacheDependency fileDep = new CacheDependency(filePath); HostingEnvironment.Cache.Insert("transDoc", doc,fileDep); } XmlNode xn = doc.SelectSingleNode(string.Format("/configuration/p[@key='{0}']",expression)); if (xn != null) { return ((XmlElement)xn).GetAttribute("value"); } return expression; } public override object EvaluateExpression(object target, BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context) { return GetEvalData(entry.Expression, target.GetType(), entry.Name); } public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context) { Type type1 = entry.DeclaringType; PropertyDescriptor descriptor1 = TypeDescriptor.GetProperties(type1)[entry.PropertyInfo.Name]; CodeExpression[] expressionArray1 = new CodeExpression[3]; expressionArray1[0] = new CodePrimitiveExpression(entry.Expression.Trim()); expressionArray1[1] = new CodeTypeOfExpression(type1); expressionArray1[2] = new CodePrimitiveExpression(entry.Name); return new CodeCastExpression(descriptor1.PropertyType, new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(base.GetType()), "GetEvalData", expressionArray1)); } public override bool SupportsEvaluate { get { return true; } } } }
翻译文件为Translate.config.格式如下:
<?xml version="1.0" encoding="utf-8"?> <configuration> <p key="_welCom_" value="You Are Welcome!"/> </configuration>
好了,现在在web.config里配置就可以使用了。web.config配置如下:
<?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <compilation debug="true" targetFramework="4.0"> <expressionBuilders> <add expressionPrefix="SPExpression" type="ExpressionBuilderTest.Library.SPExpressionBuilder"/> </expressionBuilders> </compilation> </system.web> </configuration>
在页面上拖一个label
<asp:Label ID="Label1" runat="server" Text="<%$SPExpression:_welCom_ %>"></asp:Label>
即可实现翻译。