从 URL 访问 png 图像时出现基本 Url 问题

Base Url Issue when accessing png image from a URL

我正在使用 ASP.NET 核心托管的 Blazor Web 程序集。 我已将 Base URL 设置为 "/"

我想将图像从 URL 转换为字节数组 所以我使用下面的代码来转换

string imageUrl = "https://homepages.cae.wisc.edu/~ece533/images/frymire.png";
var imageBytes = await File.ReadAllBytesAsync(imageUrl);

但 Blazor Web Assembly 在运行时出现以下错误

blazor.webassembly.js:1 crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100] Unhandled exception rendering component: Could not find a part of the path "https:/homepages.cae.wisc.edu/~ece533/images/frymire.png". System.IO.DirectoryNotFoundException: Could not find a part of the path "/https:/homepages.cae.wisc.edu/~ece533/images/frymire.png". at System.IO.FileStream..ctor (System.String path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, System.Int32 bufferSize, System.Boolean anonymous, System.IO.FileOptions options) <0x2de83f8 + 0x00258> in :0 at System.IO.FileStream..ctor (System.String path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, System.Int32 bufferSize, System.IO.FileOptions options) <0x35ad778 + 0x0001c> in :0 at System.IO.File.ReadAllBytesAsync (System.String path, System.Threading.CancellationToken cancellationToken) <0x35a9718 + 0x0003a> in :0 at SlashCare.Client.Pages.Admin.Category.CategoryComponent.EditCategoryOpenAsync (System.Guid categoryId) [0x0011f] in D:\Projects\SlashCare\Client\Pages\Admin\Category\CategoryComponent.razor.cs:72 at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion (System.Threading.Tasks.Task task) <0x2f9d710 + 0x000da> in :0 at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask (System.Threading.Tasks.Task taskToHandle) <0x2f9a270 + 0x000b6> in :0

正如我在错误中看到的那样 / 自动附加到导致此问题的路径

这个问题有什么解决办法吗?

您需要使用 HttpClient 从 URL 而不是文件中获取数据。

使用 HTTP 请求而不是文件:

@inject HttpClient _httpClient

@code {
    private async Task LoadFileAsync()
    {
         string imageUrl = "https://homepages.cae.wisc.edu/~ece533/images/frymire.png";
         using var response = await _httpClient.GetAsync(imageUrl).ConfigureAwait(false);
         var imageBytes = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
    }
}