3

In an MVC project, I have a method on a hub similar to this:

public string Foo() { return DoCrazyThingThatReturnsJson(); }

Unfortunately SignalR (or something) takes the encoded JSON string and happily encodes it, then returns it, so browser be like LOLWTF. Is there a way to skip this second encoding?

Lars Höppner
  • 18,252
  • 2
  • 45
  • 73
Josh
  • 6,944
  • 8
  • 41
  • 64

1 Answers1

0

Looking at this here:

We assume that any ArraySegment is already JSON serialized

it seems like something like this may work (note that I haven't tried it, so no promises):

string jsonString = ...; // your serialized data
var jsonBytes = new ArraySegment<byte>(Encoding.UTF8.GetBytes(jsonString));
Clients.Caller.sendJson(jsonBytes);

(The above only works for PersistentConnection because of what constitutes a value - for hubs, the data is wrapped in a container with the RPC info; I'm only leaving this in case using PersistentConnection is an option for you)

Another idea might be creating a container class for a JSON string, then using a custom converter that simply writes the string as-is, then register like this in the Signalr startup code:

var serializer = new JsonSerializer();
serializer.Converters.Add(new PreserializedConverter());

GlobalHost.DependencyResolver.Register(typeof(JsonSerializer), () => serializer);
Lars Höppner
  • 18,252
  • 2
  • 45
  • 73