announcements icon indicating copy to clipboard operation
announcements copied to clipboard

Byte Array Interop in .NET 6.0 Preview 6

Open TanayParikh opened this issue 4 years ago • 0 comments

Summary

Blazor Server & WebAssembly now supports optimized byte array interop which avoids encoding/decoding byte arrays into Base64, facilitating a more efficient interop process.

Breaking Change

Receiving Byte Arrays in JS

function ReceivesByteArray(data)
{
	// Previously data was a Base 64 encoded string representing the byte array
	// 6.0 Preview 6 and beyond, it'll be a Uint8Array (no longer requires processing the Base 64 encoding)
}

which can be invoked by the following C# code:

var bytes = new byte[] { 1, 5, 7 };
await _jsRuntime.InvokeVoidAsync("ReceivesByteArray", bytes);

Sending Byte Arrays from JS

If .NET is expecting a byte[] JS must provide a Uint8Array. Previously, it was possible to provide a Base64 encoded array using btoa.

For example, if you have something like this:

var bytes = await _jsRuntime.InvokeAsync<byte[]>("someJSMethodReturningAByteArray");

then you must provide a Uint8Array from JS (must not be Base 64 encoded).

Before:

function someJSMethodReturningAByteArray() {
    const data = new Uint8Array([ 1, 2, 3 ]);
    const base64EncodedData = btoa(String.fromCharCode.apply(null, data as unknown as number[]));
    return base64EncodedData;
}

After:

function someJSMethodReturningAByteArray() {
    const data = new Uint8Array([ 1, 2, 3 ]);
    return data;
}

PR: https://github.com/dotnet/aspnetcore/pull/33015 Issue: https://github.com/dotnet/aspnetcore/issues/21877

TanayParikh avatar Jun 07 '21 21:06 TanayParikh