虽然Blazor提供了C#/JS互操作,但它只能在浏览器中工作,并且是为SPA设计的。微软似乎不打算增加对其他场景的支持:https://github.com/dotnet/aspnetcore/issues/37910
是否可以在JavaScript中使用C#程序和库,而不依赖于DOM或其他特定于环境的API?
使用的自定义构建是可能的。NET WebAssembly运行时和环境无关的JavaScript包装器。
这里有一个解决方案,它使用这样的自定义构建来允许将C#项目编译到UMD库中,UMD库可以在浏览器、node.js和自定义限制环境中使用,例如VS Code的web扩展:https://github.com/Elringus/DotNetJS
要使用它,请指定Microsoft.NET.Sdk.BlazorWebAssembly
SDK并导入DotNetJS
NuGet包:
<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="DotNetJS" Version="*"/>
</ItemGroup>
</Project>
要将JavaScript函数与C#方法关联,请使用JSFunction
属性。要向JavaScript公开C#方法,请使用JSInvokable
属性:
using System;
using DotNetJS;
using Microsoft.JSInterop;
namespace HelloWorld;
partial class Program
{
// Entry point is invoked by the JavaScript runtime on boot.
public static void Main ()
{
// Invoking 'dotnet.HelloWorld.GetHostName()' JavaScript function.
var hostName = GetHostName();
// Writing to JavaScript host console.
Console.WriteLine($"Hello {hostName}, DotNet here!");
}
[JSFunction] // The interoperability code is auto-generated.
public static partial string GetHostName ();
[JSInvokable] // The method is invoked from JavaScript.
public static string GetName () => "DotNet";
}
使用dotnet publish
发布项目。单个文件CCD_ 6库将在";bin";目录根据环境消耗库:
浏览器
<!-- Import as a global 'dotnet' object via script tag. -->
<script src="dotnet.js"></script>
<script>
// Providing implementation for 'GetHostName' function declared in 'HelloWorld' C# assembly.
dotnet.HelloWorld.GetHostName = () => "Browser";
window.onload = async function () {
// Booting the DotNet runtime and invoking entry point.
await dotnet.boot();
// Invoking 'GetName()' C# method defined in 'HelloWorld' assembly.
const guestName = dotnet.HelloWorld.GetName();
console.log(`Welcome, ${guestName}! Enjoy your global space.`);
};
</script>
Node.js
// Import as CommonJS module.
const dotnet = require("dotnet");
// ... or as ECMAScript module in node v17 or later.
import dotnet from "dotnet.js";
// Providing implementation for 'GetHostName' function declared in 'HelloWorld' C# assembly.
dotnet.HelloWorld.GetHostName = () => "Node.js";
(async function () {
// Booting the DotNet runtime and invoking entry point.
await dotnet.boot();
// Invoking 'GetName()' C# method defined in 'HelloWorld' assembly.
const guestName = dotnet.HelloWorld.GetName();
console.log(`Welcome, ${guestName}! Enjoy your module space.`);
})();