如何使用 Blazor 渲染知道其内容类型的字节数组?

How to render byte array knowing its content-type using Blazor?

以下代码对应一个Blazor服务端页面:

    @page "/ShowFile/{Id:guid}"

    //// 放在这里让浏览器渲染存储在 this.Model 上的字节数组
    //// 还有如何指定响应的内容类型?

    @代码
    {
        [范围]
        public Guid ID { get;放; }

        私人字节[]模型{得到;放; }

        受保护的覆盖异步任务 OnInitializedAsync()
        {
            等待 base.OnInitializedAsync();
            //// 根据标识符获取文件的字节数组。
            this.Model = await this.GetFile(this.Id).ConfigureAwait(false);
        }
    }

在 ASP.NET MVC 中,我曾经在控制器操作中这样做:

    this.Response.ContentType = "application/pdf"; //// 假设字节数组表示一个 PDF 文档。
    等待 this.Response.Body.WriteAsync(this.Model);

如何让浏览器根据其内容类型在我的页面中呈现字节数组?

@page "/test"
@inject HttpClient Http

@if (!string.IsNullOrEmpty(pdfContent))
{
    <embed src="@pdfContent" width="800px" height="2100px" />
    <iframe src="@pdfContent" width="800px" height="2100px" />
    <object data="@pdfContent" width="500" height="200"></object>
}


@code {
    string pdfContent = "";

    protected async override Task OnInitializedAsync()
    {
        var data = await Http.GetByteArrayAsync("the source you pdf");

        pdfContent = "data:application/pdf;base64,";
        pdfContent += System.Convert.ToBase64String(data);
    }
}

我在客户端 blazor 上试过了,它在那里工作。在服务器端试一试。

我设法通过 回答在服务器端 Blazor 上运行。获得 Base64 字符串后,我必须使用 StateHasChanged() 重新呈现页面。

@page "/Document/Open/{documentId:int}"

@if (!string.IsNullOrEmpty(pdfContent))
{
    <embed src="@pdfContent" width="800px" height="2100px" />
    <iframe src="@pdfContent" width="800px" height="2100px" />
    <object data="@pdfContent" width="500" height="200"></object>
}


@code {
    [Parameter]
    public int DocumentId { get; set; }
    string pdfContent = "";

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            var apiService = await CreateClient();
            var data = await apiService.Open(DocumentId);
            pdfContent = "data:application/pdf;base64,";
            pdfContent += System.Convert.ToBase64String(data);
            StateHasChanged();

        }
    }
}

第一次呈现页面时,我创建了一个在其构造函数中采用 HTTP 客户端的服务实例。然后我调用方法 Open,它 returns 来自 Azure Blob 存储的字节数组。