5

在 WASI 上运行 .NET 7 应用程序

 2 years ago
source link: https://www.cnblogs.com/shanyou/p/16098911.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

在 WASI 上运行 .NET 7 应用程序

WASI代表 WebAssembly 系统接口,WASI 让沙盒化的 WebAssembly 应用程序通过一系列类似 POSIX 的函数访问底层操作系统,允许独立于浏览器运行 WebAssembly 代码。这是一个高度实验性的项目,但同时也是一个非常有趣的项目,并且有可能为行业的大规模编程范式转变做出贡献,使 WebAssembly 真正无处不在。

微软的 Steve Sanderson 最近发布了.NET 的实验性WASI SDK for .NET的第一个版本,它允许将 .NET 7 和 ASP.NET Core 应用程序 构建为独立的 WASI 兼容应用程序,并从 WASI 主机运行它们。Steve 的 repo 提供了在 Windows 和 Linux 上使用的简单步骤.

我们首先要安装 .NET 7 SDK。最新的是预览7.0.100-preview.2并不能运行, Steve 提交了有个PR https://github.com/dotnet/aspnetcore/pull/40376 需要 7.0.100-preview.4以上版本修复,运行时方面的相关 PR 可以在https://github.com/dotnet/runtime/pull/67036 找到 ,考虑到所有因素,因为它已经修复,只是不是“正式可用”,所以最好的办法是从每日构建版本https://github.com/dotnet/installer/blob/main/README.md#installers-and-binaries 安装适用于对应操作系统的SDK,比如Windows的最新稳定版本是 https://aka.ms/dotnet/7.0.1xx/daily/dotnet-sdk-win-x64.exe,例如,我今天安装的当前可用版本是7.0.100-preview.4.22201.11。

我们创建一个常规的基本 ASP.NET Core Web 应用程序。

dotnet new web

项目创建后,需要添加以下包引用才能引入实验 Wasi.Sdk以及 Steve 构建的相应 ASP.NET Core 服务器实现:

<ItemGroup>
    <PackageReference Include="Wasi.AspNetCore.Server.Native" Version="0.1.0" />
    <PackageReference Include="Wasi.Sdk" Version="0.1.0" />
  </ItemGroup>

除此之外,main PropertyGroup 下的一个额外属性,一个与您的应用程序使用的端口 在launchSettings.json 相对应的端口:

<WasiRunnerArgs>--tcplisten localhost:5100 --env ASPNETCORE_URLS=http://localhost:5100</WasiRunnerArgs>

由于我们的应用程序需要从 WASI 主机内部侦听网络接口,因此需要在生成的代码中进行额外的更改,即需要添加WasiConnectionListener() 到默认值WebApplication 构建者:

var builder = WebApplication.CreateBuilder(args).UseWasiConnectionListener();

此时应用程序将正确构建,但它还无法运行,因为我们还需要有 WASI 主机可供我们使用。

为了运行这个基于 WASI 的应用程序,我们需要一个 WASI 运行时。一个优秀的轻量级运行时是wasmtime,它恰好是这个实验使用的那个Wasi.Sdk ,我们需要 它在 PATH 上可用。

我们应该能够运行应用程序:

打开浏览器访问 http://localhost:5100/ ,我们现在应该在其中看到我们的 hello world。 以一种非常壮观的方式,我们现在有一个在 WASI 运行时中作为 WebAssembly 应用程序运行的ASP.NET Core应用程序 ,并且可以从浏览器访问。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK