Is it possible to return a pre-encoded JSON string in a SignalR hub method?

两盒软妹~` 提交于 2020-01-02 07:05:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!