ASP.NET中使用CodeDomProvider调用js文件中的js方法
ASP.NET中使用CodeDomProvider调用js文件中的js方法一、新建 test.js文件
public static function getJsResponse(str) {
var $t = "2";
var $u = new Date();
var $v = new Date($u.getTime() + 315360000000);
var $w = new Date($u.getTime());
if ($t.length < 10) {
var $x = $u.getTime().toString();
for (var i = 2; i <= (32 - $x.length); i++) $t += Math.floor(Math.random() * 16.0).toString(16);
$t += $x;
};
$t = encodeURIComponent($t);
return "WT_FPC=id=" + $t + ":lv=" + $u.getTime().toString() + ":ss=" + str ;
}
二、动态编译、执行Js代码的方法
public static class JsHelper
{
/// <summary>
/// 执行JS方法
/// </summary>
/// <param name="methodName">方法名</param>
/// <param name="para">参数</param>
/// <param name="filePath">js文件路径</param>
/// <returns></returns>
public static string GetJsMethd(string methodName, object[] para,string filePath)
{
string path = AppDomain.CurrentDomain.BaseDirectory + filePath;
string str2 = System.IO.File.ReadAllText(path);
StringBuilder sb = new StringBuilder();
sb.Append("package aa{");
sb.Append(" public class JScript {");
sb.Append(str2);
sb.Append("}}");
CompilerParameters parameters = new CompilerParameters();
parameters.GenerateInMemory = true;
CodeDomProvider _provider = new Microsoft.JScript.JScriptCodeProvider();
CompilerResults results = _provider.CompileAssemblyFromSource(parameters, sb.ToString());
//如果JS有错,这里会报 找不到某个 .dll 的错误,我们可以利用下面的语句捕获到具体的错误信息。
if (results.Errors.Count > 0)
{
Console.WriteLine("Errors:");
foreach (CompilerError ce in results.Errors)
{
string errorMessage=ce.ToString();
}
}
Assembly assembly = results.CompiledAssembly;
Type _evaluateType = assembly.GetType("aa.JScript");
object obj = _evaluateType.InvokeMember(methodName, BindingFlags.InvokeMethod,
null, null, para);
return obj.ToString();
}
}
三、调用
public string Main()
{
object[] para = new object[] { "学习也休闲" };
string wt_fpc = JsHelper.GetJsMethd("getJsResponse", para, @"Scripts\\\\test.js");
return wt_fpc;
}
结果如图