问题
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?
回答1:
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);
来源:https://stackoverflow.com/questions/28547575/is-it-possible-to-return-a-pre-encoded-json-string-in-a-signalr-hub-method