You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core 8 WASM项目:如何用JSImport带参调用JS函数?

ASP.NET Core 8 WASM带参数JSImport互操作实现

修正C#侧声明(可选但推荐)

你的原JSImport写法中,第一个参数填window.location.test不符合模块导入规范,建议调整为模块内的导出函数名,示例如下:

[JSImport("test", "main.js")]
internal static partial string Test(string a, int b);

如果一定要使用挂载到window.location的全局函数,可以改用globalThis参数声明:

[JSImport("window.location.test", globalThis: true)]
internal static partial string Test(string a, int b);

对应JavaScript实现

方式1:模块导入(推荐)

在项目wwwroot下的JavaScript文件中,通过setModuleImports注册main.js模块的实现,函数参数顺序、类型需与C#方法完全对应:

// 初始化.NET运行时
const dotnetRuntime = await dotnet.createRuntime();

// 注册模块及对应函数
dotnetRuntime.setModuleImports("main.js", {
  test: (inputStr, inputNum) => {
    // 处理参数并返回字符串,示例为拼接参数内容
    return `接收到字符串参数:${inputStr},数字参数:${inputNum}`;
  }
});

方式2:全局函数挂载

如果用了globalThis: true的C#声明,直接在全局挂载函数即可,无需setModuleImports:

window.location.test = (inputStr, inputNum) => {
  return `参数1:${inputStr},参数2:${inputNum}`;
};

调用验证

在C#代码中直接调用分部方法即可完成带参数互操作:

string result = Test("WASM互操作", 8);
// result将返回JS函数处理后的字符串

注意:参数类型会自动双向转换(如C#的int对应JS的number,string对应JS的string),只需确保参数顺序一致即可。

内容的提问来源于stack exchange,提问作者jawk97

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 22:37:39