且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Blazor读取服务器端文件

更新时间:2023-02-17 10:57:16

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

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.