使用 Blazor 读取服务器端文件 [英] Reading server-side files using Blazor

查看:64
本文介绍了使用 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.ReadAllText("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.

这篇关于使用 Blazor 读取服务器端文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆