Search code examples
.netblazor-webassemblywebassembly

Pass .NET objects to JS wasm


I want to write code like this and be able to read the properties of the object in JS:

[JSExport]
[return: JSMarshalAs<JSType.Any>]
internal static IEntry GetEntry(string id)
{
    return _api.GetEntry(id);
}

This code gives me the error:

The type 'lexboxClientContracts.IEntry' is not supported by source-generated JavaScript interop. The generated source will not handle marshalling of the return value of method 'GetEntry'. For more information see https://aka.ms/dotnet-wasm-jsinterop (SYSLIB1072)

I've gone over the documentation many times and it's just not clicking for me. So it seems likely that the answer is just "no" and I have to serialize it myself, but that seems silly.

If I change the return type to object, the code runs and I get a ManagedObject in JS that I don't know what to do with (also can't find any documation on that).

[JSExport]
[return: JSMarshalAs<JSType.Any>]
internal static object GetEntry(string id)
{
    return _api.GetEntry(id);
}

Note: I'm not actually using Blazor, but that seems the best way to lable this .NET/wasm stuff.


Solution

  • I finally found the appropriate GitHub issue: https://github.com/dotnet/runtime/issues/77784

    In summary, it is currently necessary to explicitly/manually serialize and deserialize. The issue suggests introducing the type JSType.Json, which would cause the object to get serialized (and hopefully deserialized) automatically.