简体   繁体   中英

Read local/static file in Blazor Wasm

My project is created in Blazor WASM ( I do not want to use Blazor server )

I would like to read XSD files from wwwroot:

在此处输入图像描述

Inside my XsdService.cs - c# class I was trying:

string pathToXsd = Path.Combine("plcda","extPL_r2.xsd");
string transformataHTML = System.IO.File.ReadAllText(pathToXsd);

However, I always get errors:

Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
      Unhandled exception rendering component: Could not find a part of the path "/plcda/extPL_r2.xsd".
System.IO.DirectoryNotFoundException: Could not find a part of the path "/plcda/extPL_r2.xsd".

So is there any chance to include custom/static/local files to Blazor WASM? And read them even if app is offline?

Create a Http GET call to the files. Think of Blazor wasm as a SPA application. All of the files that are required to run your app are downloaded into a users browser. Everything else like images are fetched on request. Like an images is requested by the browser.

@inject HttpClient _client

@code {
    async Task GetXDSFile()
    {
        var byteOfTheFile = await _client.GetByteArrayAsync("plcda/extPL_r2.xsd");
    }
}

This sample just fetches the file as byte array. Other version of the Get maybe more sutaible for you like GetStreamAsync .

In .NET Core 6 you can add provider mappings to your client project's program.cs to serve static files.

For example I need to load a 3d model (.obj, .mtl files):

Blazor WASM Client Only Project :

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.StaticFiles;


var provider = new FileExtensionContentTypeProvider();
provider.Mappings.Add(".obj", "application/obj");
provider.Mappings.Add(".mtl", "application/mtl");

builder.Services.Configure<StaticFileOptions>(options =>
{
    options.ContentTypeProvider = provider;
});

await builder.Build().RunAsync();

If you have an asp.net core hosted project you can simply put this in the server project's program.cs file instead and you shouldn't need to add nuget package references.

Blazor WASM Asp.net Core Hosted Project :

using Microsoft.AspNetCore.StaticFiles;


var provider = new FileExtensionContentTypeProvider();
provider.Mappings.Add(".babylon", "application/javascript");
provider.Mappings.Add(".obj", "application/obj");
provider.Mappings.Add(".mtl", "application/mtl");
builder.Services.Configure<StaticFileOptions>(options =>
{
    options.ContentTypeProvider = provider;
});

var app = builder.Build();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM