DEV Community

Zero Heartbeat
Zero Heartbeat

Posted on Originally published at delta1labs.com

Keep Blazor JS interop working after obfuscation

A Blazor app ships, obfuscated, and a button that worked all through development now fails in production:

Microsoft.JSInterop.JSException: The assembly 'MyApp' does not contain
a public invokable method with [JSInvokable("ComputeTotal")].
Enter fullscreen mode Exit fullscreen mode

The method is still there. It is still public. It still carries [JSInvokable]. The call still works in an un-obfuscated build. The only thing that changed is that a renaming pass turned ComputeTotal into a. That one rename broke a contract that lives half in .NET and half in a JavaScript string literal — and the fix tells you something precise about where Blazor keeps the name it matches against.

The real question

JavaScript calls into .NET by name:

const total = await DotNet.invokeMethodAsync('MyApp', 'ComputeTotal', [1, 2, 3]);
Enter fullscreen mode Exit fullscreen mode

Two strings cross the boundary: the assembly's simple name and a method identifier. Nothing on the JavaScript side knows about IL, metadata tokens, or your renamed symbols. So the question is: when the Blazor dispatcher receives ('MyApp', 'ComputeTotal'), what does it compare that identifier against — and can obfuscation change the answer?

Where the identifier comes from

When the runtime first needs a callable method, DotNetDispatcher scans the target assembly for methods marked [JSInvokable] and builds a lookup keyed by identifier. The logic that assigns each identifier is, in essence, this:

// Paraphrased from ASP.NET Core's DotNetDispatcher scan
foreach (var method in type.GetMethods(BindingFlags.Public | ...))
{
    var attribute = method.GetCustomAttribute<JSInvokableAttribute>();
    if (attribute is null) continue;

    // The identifier the JS side must send:
    var identifier = attribute.Identifier ?? method.Name;
    cache[identifier] = (method, GetParameterTypes(method));
}
Enter fullscreen mode Exit fullscreen mode

That single ?? method.Name is the whole story. JSInvokableAttribute exposes an optional identifier:

public sealed class JSInvokableAttribute : Attribute
{
    public string? Identifier { get; }
    public JSInvokableAttribute() { }                       // Identifier == null
    public JSInvokableAttribute(string identifier) => Identifier = identifier;
}
Enter fullscreen mode Exit fullscreen mode

If you used the parameterless [JSInvokable], Identifier is null, and the dispatcher falls back to method.Name. At the moment Blazor builds its table, method.Name is read from metadata at runtime — after obfuscation. So the table ends up keyed by a, while JavaScript keeps sending ComputeTotal. Lookup miss, exception.

The dispatcher keys its table by attribute.Identifier ?? method.Name. An explicit identifier moves the JS contract off the renamed member and into the attribute blob.

The fix: move the contract into the attribute

Pin the identifier explicitly, and let the method name be renamed to whatever the obfuscator likes:

public class Interop
{
    [JSInvokable("ComputeTotal")]                 // identifier is now a literal
    public static Task<int> ComputeTotal(int[] values)
        => Task.FromResult(values.Sum());
}
Enter fullscreen mode Exit fullscreen mode

After obfuscation the method might be MyApp.a.b, but the dispatcher reads attribute.Identifier, finds "ComputeTotal", and registers the table under that key. JavaScript is unchanged. The method is fully renamed — its CLR name reveals nothing — yet the boundary holds.

The reason this is robust comes down to where each name is stored in the PE file. A method's name is the Name column of its MethodDef row in the #Strings heap; renaming rewrites exactly that. An attribute argument such as "ComputeTotal" is serialized into the custom-attribute #Blob heap as part of the attribute's value, and it is referenced by the CustomAttribute table, not by any ldstr instruction. Two consequences follow:

  • Renaming never touches it. Renaming operates on definition names, not on attribute blob contents.
  • String encryption never touches it either. Nebula's string encryption rewrites ldstr instructions in method bodies; an attribute argument is not a ldstr, so an encrypted-strings build keeps the identifier in clear form where the dispatcher can read it. You get both passes and a working boundary.

This is the same discipline that makes [JsonPropertyName] the right way to protect a JSON contract: the member you want to rename stops being the thing the outside world depends on.

Instance methods and the assembly-name coupling

Static invocation couples JavaScript to your assembly's simple name — the first argument to invokeMethodAsync. Obfuscators rarely rename the assembly identity, but if your build renames or repackages it, every static call breaks too. Instance interop avoids that coupling entirely. You hand JavaScript a reference and it calls methods on that object without naming an assembly:

public sealed class Counter
{
    private int _count;

    [JSInvokable("Increment")]
    public int Increment() => ++_count;
}

// Registering the reference with JS:
var objRef = DotNetObjectReference.Create(new Counter());
await JS.InvokeVoidAsync("app.registerCounter", objRef);
Enter fullscreen mode Exit fullscreen mode
// Only the identifier crosses — no assembly name:
window.app = {
  registerCounter: (ref) => ref.invokeMethodAsync('Increment')
};
Enter fullscreen mode Exit fullscreen mode

Instance references keep the public surface small (you expose one object, not a flat assembly-wide method table) and remove the assembly-name dependency. Combined with explicit identifiers, the only name the JavaScript world ever learns is the one you chose to publish.

How to configure it

The attribute-identifier approach needs nothing special from Nebula — that is the point. Renaming stays fully on, string encryption stays on, and there is no keep-list entry for these methods. Two settings must simply remain at their safe defaults:

  • Keep custom attributes. Blazor finds callable methods by reflecting for JSInvokableAttribute at runtime, so the attribute must survive into the shipped assembly. Nebula preserves attributes by default; do not enable an aggressive "strip attributes" option for a Blazor assembly.
  • Do not reduce accessibility. A JS-invokable method must stay public. If you run a pass that demotes "unused" public members to internal, these methods look unused (nothing in managed code calls them) and get demoted, which also removes them from the dispatcher's scan.

When it breaks

  • Generic methods. Blazor JS interop does not support open generic [JSInvokable] methods, obfuscated or not. That is a framework limit, not a renaming issue.
  • DTO property names still matter. Arguments and return values cross as JSON. Renaming a property on a complex argument type changes its serialized name just as it would for any System.Text.Json payload — protect those with [JsonPropertyName] the same way you protect the identifier. See obfuscating System.Text.Json contracts.
  • [JSExport] is the opposite case. The newer marshaled WebAssembly interop (System.Runtime.InteropServices.JavaScript) has no identifier override. JavaScript reaches an exported method through its namespace, type and method name:
  const exports = await getAssemblyExports('MyApp.dll');
  exports.MyApp.Interop.ComputeTotal(/* ... */);
Enter fullscreen mode Exit fullscreen mode

Here the managed names are the contract. Rename the namespace, the type, or the method and that path stops resolving, and there is no attribute string to fall back on. [JSExport] methods, and the types and namespaces that form their call path, must go on the Nebula keep-list. Recognising which interop system a method uses — string-dispatched [JSInvokable] versus name-bound [JSExport] — is the whole decision.

Takeaway

Blazor's [JSInvokable] boundary matches on a string, and by default that string is your method's CLR name — exactly the thing you pay an obfuscator to destroy. Give every JS-callable method an explicit identifier and the contract moves into the custom-attribute blob, where neither renaming nor string encryption can reach it. Then rename everything. The method that JavaScript calls can have a one-letter name in the shipped binary and still answer to the stable identifier you published. For the name-bound [JSExport] path, do the reverse and keep the names — knowing which rule applies is the entire trick. Nebula protects the method body while you keep the one string the boundary depends on.

Top comments (0)