在Nodejs中如何调用C#的代码


最近需要在Nodejs中用到C#的代码,从网上了解到可以采用Edgejs来实现Nodejs与C#的代码交互,

直接复制网上的代码运行总是出各种错,填了不少坑,现在把自己的案例代码大致整理一下,方便以后自己查询。

 

一、安装Edge.js

运行命令行(CMD),进入当前项目的目录,执行命令“npm install edge”进行安装。(这里也可以选择全局安装,具体操作就不说了)

 

二、调用Edge.js

在用Edge.js和C#代码交互的时候,有三种方式:

1. 第一种方式是将c#的代码封装成dll,然后在nodejs里面调用

代码示例如下:

Nodejs:
// 引入Edge模块var edge = require('./node_modules/edge'); // 定义方法var StudyMath = edge.func({
assemblyFile:
'../../_lib/Rocky.dll', // assemblyFile为dll路径 atypeName: 'RockyNamespace.Study', // RockyNamespace为命名空间,Study为类名 methodName: 'StudyMath' // StudyMath为方法名}); // s为传递方法传递的参数,result为方法返回的结果 StudyMath (s, function (error, result) { if (error) throw error; if (0 == result) ; // Successelse ; // Failure });

 

C#:

namespace RockyNamespace {  public class Study {  // C#中,方法必须用async异步修饰,且返回值必须为Task<object>,其中,input即为方法的参数,上文的s => input
 public async Task<object> StudyMath(object input) {  // 方法体
 return 0; } } }

 

 

2. 第二种方式是将c#的代码用async处理后直接在nodejs中书写:

代码示例如下:

Nodejs:
var edge = require('./node_modules/edge'); var StudyMath = edge.func(function () {/* //using System.Reflection; using System.Collections.Generic; async (input) => { // 方法体 return 0; } */});
// s为传递方法传递的参数,result为方法返回的结果 StudyMath (s, function (error, result) { if (error) throw error; if (0 == result) ; // Success else ; // Failure });

 

3. 第三种方式是第一种和第二种的结合

代码示例如下:

Nodejs:

var edge = require('./node_modules/edge'); var StudyMath = edge.func(function () {/* using System.Collections.Generic; using System.Threading.Tasks; namespace RockyNamespace { public class Startup { // C#中,方法必须用async异步修饰,且返回值必须为Task<object>,其中,input即为方法的参数,上文的s => input public async Task<object> Invoke(object input) { // 方法体 return 0; } } } */});
// s为传递方法传递的参数,result为方法返回的结果 StudyMath (s, function (error, result) { if (error) throw error; if (0 == result) ; // Success else ; // Failure });
 
需注意的是,采用第三种方式的时候,必须将类名命名成Startup,方法名命名为Invoke,
因为在edge内部中,会默认将typeName定义为Startup,将methodName定义为Invoke
类似如下的定义:
var func= edge.func({
  typeName: 'Startup',
  methodName: 'Invoke'
});

 

Edgejs官网:

http://tjanczuk.github.io/edge/#/

 

这里推荐一篇写的比较详细的文章:

http://blog.csdn.net/kimmking/article/details/42708049


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM