Elr*_*gus 6 javascript c# interop webassembly blazor-webassembly
要将 C# 编译为 WebAssemly 并与 JS 互操作,需要使用 Blazor WebAssembly ASP.NET 框架,该框架是为 SPA 设计的,如果您只想使用 JS 中的 C# 库,则会产生大量开销。
将 DLL 编译为 WebAssembly 并从 JavaScript 使用它的最低设置是什么?
Elr*_*gus 11
更新:从 .NET 7 开始,用例具有第一方支持:https://devblogs.microsoft.com/dotnet/use-net-7-from-any-javascript-app-in-net-7/下面是仍然与旧的 .NET 版本相关,或者如果您想更深入地挖掘和/或实现自定义互操作层。
使用以下配置创建一个新的空 C# 项目(通过 .csproj):
<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<LangVersion>10</LangVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="6.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="6.0.0" PrivateAssets="all" />
</ItemGroup>
</Project>
Run Code Online (Sandbox Code Playgroud)
初始化 Blazor JS 运行时并指定绑定:
<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<LangVersion>10</LangVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="6.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="6.0.0" PrivateAssets="all" />
</ItemGroup>
</Project>
Run Code Online (Sandbox Code Playgroud)
通过 JS发布dotnet publish并使用 C# 库:
namespace WasmTest;
public class Program
{
private static IJSRuntime js;
private static async Task Main (string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
var host = builder.Build();
js = host.Services.GetRequiredService<IJSRuntime>();
await host.RunAsync();
}
[JSInvokable]
public static async Task<string> BuildMessage (string name)
{
var time = await GetTimeViaJS();
return $"Hello {name}! Current time is {time}.";
}
public static async Task<DateTime> GetTimeViaJS ()
{
return await js.InvokeAsync<DateTime>("getTime");
}
}
Run Code Online (Sandbox Code Playgroud)
或者,这里有一个解决方案,允许将 C# 项目编译成单文件 UMD 库,该库可以在任何 JavaScript 环境中使用:浏览器、节点和自定义受限环境,例如 VS Code 的 Web 扩展:https://github。 com/Elringus/DotNetJS