9

【ASP.NET Core】在node.js上托管Blazor WebAssembly应用 - 东邪独孤

 2 years ago
source link: https://www.cnblogs.com/tcjiaan/p/17241935.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.
neoserver,ios ssh client

【ASP.NET Core】在node.js上托管Blazor WebAssembly应用

由于 Blazor-WebAssembly 是在浏览器中运行的,通常不需要执行服务器代码,只要有个“窝”能托管并提供相关文件的下载即可。所以,当你有一个现成的 Blazor wasm 项目,没必要用其他语言重写,或者你不想用 ASP.NET Core 来托管(有些大材小用了),就可以试试用 node.js 来托管。

要实现这个不需要掌握什么新的知识,所以咱们直接开工干活。

首先,咱们做好 Blazor wasm 应用的开发。

dotnet new blazorwasm-empty -n Demo -o .

blazorwasm-empty 模板创建的项目只带一些基本代码和 Hello World,没有演示代码——无Counter无假天气预报。

然后,Program.cs 文件也可以精简一下。

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");

await builder.Build().RunAsync();

#app 是CSS筛选器,即选择 id 为 app 的元素来呈现 Razor 组件。这个相信各位都懂。

为了更好地演示,咱们把 Index 组件改一下,加一点交互功能,以便后面可以验证 Blazor 是否正常启动。

@page "/"

<h1>Hello, world!</h1>
<button @onclick="ClickMe">点这里中大奖</button>
<div>@Message</div>

@code{
    private string? Message{get;set;}

    void ClickMe()
    {
        int xx = Random.Shared.Next(100, 700);
        Message = $"恭喜你获得{xx}万假钞!";
    }
}

这个不复杂,就是点击一下按钮,然后生成个随机整数,并修改 Message 属性。处理 click 事件要注意加上 @,如果是 onclick 你只能用 js 去写,要想用 C# 来写代码,就得用 @onclick。

接着,试执行一下,保证没有错误,能正常运行。

367389-20230321222616832-1167090705.png

现在,你打开 \bin\Debug\net7.0\wwwroot 目录,里面你看到有个 _framework 目录,这个目录就是我们要的。不过,这个体积太大,不适合。咱们将项目发布一下,这样体积会变小很多。

我们不需要 wwwroot 目录下的东东,把整个目录“咔嚓”掉(这里指的是项目中的 wwwroot 目录,不是输出目录的)。为了防止重新生成时有文件错误(一般不会),可以把 obj 和 bin 目录也删除。

执行发布命令。

dotnet publish -c PublishRelease

-c 参数也可以用 Release,差别不大。

另外新建一个目录,路径随便,不要有非英文字符(防止出错),比如这里我命名为 Server。把刚才发布的整个 _framework 目录复制到 Server 目录中。现在你可以关闭 Blazor 项目了,没它什么事了。

在 Server 目录下新建一个文件,叫 index.html。

<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="utf-8"/>
        <title>高级示例</title>
    </head>
    <body>
        <div id="app">正在加载……</div>
        <script src="_framework/blazor.webassembly.js"></script>
    </body>
</html>

这里注意两处:

1、要有一个 id 为 app 的元素,它用来呈现组件。

2、<script> 要引用 blazor.webassembly.js 文件。

在 Server 目录下再新建一个文件,名为 app.js。这个用来写服务器主程序(js 代码)。

const url = require("node:url");
const path = require("node:path");
const http = require("node:http");
const fs = require("node:fs");

// 主机
const host = 'localhost';
// 端口
const port = 6748;
// MIME 映射
function getFileMap(fileExt)
{
    switch(fileExt)
    {
        case ".js":
        case ".mjs":
            return "text/javascript";
        case ".json":
            return "application/json";
        case ".htm":
        case ".html":
            return "text/html";
        case ".css":
            return "text/css";
        case ".jpg":
        case ".jpeg":
            return "image/jpeg";
        // 其他的自己看情况添加
        default:
            // 其余的如.dll、.gz等,就是二进制文件
            return "application/octet-stream";
    }
}

http.createServer((request, response)=>
{
    // 获取请求路径
    let reqPath = url.parse(request.url).pathname;
    // 去掉路径开头的“/”
    let fileName = reqPath.substring(1);
    // 如果空白,默认文件名 index.html
    if(fileName.length === 0)
    {
        fileName = "index.html";
    }
    // 读取文件内容
    fs.readFile(fileName, (err, data)=>{
        // 如果出错
        if(err)
        {
            // 直接回个404
            response.writeHead(404, {"Content-Type": "text/html"});
        }
        else
        {
            // 获取文件扩展名,以决定MIME类型
            let ext = path.extname(fileName);
            let mimeType = getFileMap(ext.toLowerCase());
            // 发送HTTP头
            response.writeHead(200, {"Content-Type": mimeType});
            // 发送正文
            response.write(data);
        }
        // 这一行必须,结束响应消息
        response.end();
    });
})
.listen(port, host);

console.log(`服务器:${host}:${port}`);

运行它,执行:node app.js。接着在浏览器中输入地址:http://localhost:6748。再验证 Blazor 应用程序是否成功启动。

367389-20230321232128424-612600423.png

如果看到随机数能正确生成,说明运行成功了。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK