使用 Blazor 读取服务器端文件

Reading server-side files using Blazor

我有一个基于 Blazor 示例的项目,其中包含 .Client.Server.Shared 项目。我在服务器上有一个文本文件 data.txt,我希望能够使用标准 StreamReader / System.IO.File 方法 read/write 。由于 Blazor 在沙箱中运行,我想我无法像在普通 windows 应用程序中那样访问整个文件系统?我已将文件放在 wwwroot 目录中,如果在浏览器中输入 url/data.txt,我什至可以从客户端访问该文件,以便提供文件,我不想这样做,但尝试读取该文件:

var file = File.ReadAllText("data.txt");

错误结果:

WASM: [System.IO.FileNotFoundException] Could not find file "/data.txt"

如何读取服务器端文件并对客户端隐藏它们?

WASM: [System.IO.FileNotFoundException] Could not find file "/data.txt" 是当您尝试访问本地文件时 Blazor 显示的标准消息客户端上的文件。 设计不允许从文件读取或写入文件,因为这违反了沙箱,通常由 Web Assembly 和 JavaScript.

共享

在服务器上你可以创建一个WebAPI可以在本地访问你的文件,无论是Json,文本,数据库等等,returns结果多种多样格式到调用 Blazor 方法。您可以使用身份验证和授权来限制对这些文件中数据的访问。

希望这对您有所帮助...

事实证明这比我想象的要容易。我从错误的角度接近它。要访问服务器端文件,请创建一个控制器:

using Microsoft.AspNetCore.Mvc;

namespace Favlist.Server.Controllers
{
    [Route("api/[controller]")]
    public class DataFetcher : Controller
    {
        [HttpGet("[action]")]
        public MyDataClass GetData(string action, string id)
        {
            var str = File.ReadAllText("data.txt");
            return new MyDataClass(str);
        }
    }
}

然后像这样在您的页面中调用它:

@using System.IO;
@page "/dataview"
@inject HttpClient Http

@if (data == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <p>@data.Name</p>
}

@functions {
    MyDataClass data;

    protected override async Task OnInitAsync()
    {
        data = await Http.GetJsonAsync<MyDataClass>("api/DataFetcher/GetData");
    }
}

MyDataClass 是您的自定义 class,包含您 read/write.

所需的任何内容

然后,您可以像往常一样访问服务器上的任何位置的文件。当前目录是您的 Project.Server 根文件夹。

是的,您可以从 blazor webassembly 应用程序的 wwwroot 文件夹中读取文件。 使用此代码读取您的文件

var response = await client.GetStringAsync(@"sample-data/test.xml");

要读取放置在项目中的 server-side 文件,请像这样使用:

System.IO.File.ReadAllText($"{System.IO.Directory.GetCurrentDirectory()}{@"\wwwroot\data.txt"}");

文章:https://www.peug.net/en/reading-server-side-files-using-blazor/