node-api-dotnet 简单试用

以前简单介绍过node-api-dotnet,以下是一个简单试用,集成了构建以及库调用

项目结构

如下,UserLogin.cs 是一个简单的dotnet 库,app.js 是调用

├── UserLogin.cs
├── app.js
├── node-dotnet.csproj
├── node-dotnet.sln
├── package.json
└── yarn.lock

代码简单说明

UserLogin.cs 引用shortid 一个简单token 返回

namespace Dalong;
using shortid;
public class UserLogin
{
    public string? UserName { get; set; }
    public string? Password { get; set; }
    public string? Email { get; set; }
    public UserLogin(string? userName, string? password, string? email)
    {
        UserName = userName;
        Password = password;
        Email = email;
    }
    public string GetToken()
    {   string id = ShortId.Generate();
        return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes($"{id}:{UserName}:{Password}"));
    }
}

node-dotnet.csproj cs 项目以及以及配置,注意PrivateAssets 是为了移除代码生成的依赖

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>net9.0</TargetFramework>
    <RootNamespace>node_dotnet</RootNamespace>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
    <DebugType>none</DebugType>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.JavaScript.NodeApi" Version="0.9.11" />
    <PackageReference Include="Microsoft.JavaScript.NodeApi.Generator" PrivateAssets="all" Version="0.9.11" />
    <PackageReference Include="shortid" Version="4.0.0" />
  </ItemGroup>

</Project>

app.js

const dotnet = require('node-api-dotnet/net9.0'); // 加载.net 9.0 模块

require('./bin/Release/net9.0/publish/node-dotnet'); // 加载dotnet 类库

let userlogin = new dotnet.Dalong.UserLogin("dalong","demo") // 方法调用,注意此处基于上边的可以动态生态ts 定义,开发比较方便

console.log(userlogin.GetToken());

构建&&运行

  • 构建
dotnet publish 
  • 运行
node app.js
  • 效果

说明

从使用上node-api-dotnet 还是挺方便的,尤其我们希望通过dotnet 进行node addon 开发的场景,比较快速方便

参考资料

https://microsoft.github.io/node-api-dotnet/scenarios/js-dotnet-dynamic.html

https://github.com/microsoft/node-api-dotnet/tree/main/examples/dotnet-dynamic-classlib

https://microsoft.github.io/node-api-dotnet/reference/js-dotnet-types.html

posted on 2025-06-25 08:00  荣锋亮  阅读(22)  评论(0)    收藏  举报

导航