使用Blazor读取服务器端文件

问题描述:

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

I have a project based on the Blazor sample with a .Client, .Server and .Shared projects. I have a textfile data.txt on the server that I want to be able to read/write using standard StreamReader / System.IO.File methods. Since Blazor runs in a sandbox I guess I can't access the entire filesystem as I would in a normal windows app? I've placed the file in the wwwroot directory, and I can even access the file from the client if a enter url/data.txt in the browser so the file gets served, which I don't want to alow, but trying to read that file as such:

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

导致错误:

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

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

How can I read server-side files and keep them hidden from the client?

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

Turns out this was easier than I thought. I was approaching it from the wrong angle. To access server side files, create a controller as such:

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.ReadAllTest("data.txt");
            return new MyDataClass(str);
        }
    }
}

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

And call it within your page like so:

@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是您的自定义类,其中包含您需要读取/写入的所有内容.

MyDataClass is your custom class containing whatever you need to read/write.

然后,您可以在服务器上的任意位置,完全按照通常的方式访问文件.当前目录是您的Project.Server根文件夹.

You can then access files exactly as you normally would, wherever you want on the server. The current directory is your Project.Server root folder.