C# 执行js

原文链接:https://www.cnblogs.com/Ehtan/p/4361986.html#undefined

 

添加COM引用: Microsoft Script Control 1.0

1、添加帮助类

using MSScriptControl;
using System;
using System.IO;

namespace Javascript
{
    /// 
    /// JavascriptHelper
    /// 
    public class JavascriptHelper
    {
        /// 
        /// ScriptControl
        /// 
        private ScriptControl jsControl = null;

        /// 
        /// 构造方法
        /// 
        public JavascriptHelper()
        {
            this.jsControl = new ScriptControl();
            this.jsControl.UseSafeSubset = true;
            this.jsControl.Language = "JScript";
        }

        /// 
        /// 添加js文件
        /// 
        /// js文件路径
        public void AddJavaScriptFile(string filePath)
        {
            if (!File.Exists(filePath))
            {
                throw new Exception("文件" + filePath + "不存在。");
            }

            string jsCode = File.ReadAllText(filePath);
            this.jsControl.AddCode(jsCode);
        }

        /// 
        /// 添加js代码
        /// 
        /// js代码
        public void AddJavascriptCode(string jsCode)
        {
            this.jsControl.AddCode(jsCode);
        }

        /// 
        /// 执行js
        /// 
        /// 方法名
        /// 结果
        public dynamic Excecute(string method)
        {
            return this.jsControl.Eval(method);
        }
    }
}

  

 

2、测试代码

 

using System;
using System.IO;

namespace Javascript
{
    public class Program
    {
        public static void Main(string[] args)
        {
            string plantext = "123456";
            string ciphertext = Rsa(plantext);
            Console.WriteLine(ciphertext);
            Console.ReadLine();
        }

        /// 
        /// rsa加密算法
        /// 
        /// 明文
        /// 密文
        private static string Rsa(string plantext)
        {
            JavascriptHelper jsHelper = new JavascriptHelper();
            AddJSFile(jsHelper);
            string method = string.Format("encrypt('{0}');", plantext);
            string ciphertext = jsHelper.Excecute(method).ToString();
            return ciphertext;
        }

        /// 
        /// 添加js文件
        /// 
        /// JavascriptHelper
        private static void AddJSFile(JavascriptHelper jsHelper)
        {
            string path = string.Empty;
            path = AppDomain.CurrentDomain.BaseDirectory + @"js\security.js";
            jsHelper.AddJavaScriptFile(path);

            path = AppDomain.CurrentDomain.BaseDirectory + @"js\rsa.js";
            jsHelper.AddJavaScriptFile(path);
        }
    }
}

  

你可能感兴趣的:(C# 执行js)