Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SignalR : use camel case

I would like to know if there is a way to configure SignalR so that the client functions in the hub return objects using camel case.

Thanks.

like image 778
dafriskymonkey Avatar asked May 02 '15 17:05

dafriskymonkey


People also ask

When should I use SignalR?

SignalR can be used to add any sort of "real-time" web functionality to your ASP.NET application. While chat is often used as an example, you can do a whole lot more. Any time a user refreshes a web page to see new data, or the page implements long polling to retrieve new data, it is a candidate for using SignalR.

Does SignalR use JSON?

ASP.NET Core SignalR supports two protocols for encoding messages: JSON and MessagePack. Each protocol has serialization configuration options.

How do I send client specific messages using SignalR?

SignalR allows messages to be sent to a particular client connection, all connections associated with a specific user, as well as to named groups of connections. => await Clients. User(userId).


1 Answers

Roll your own Conttract resolver like

public class SignalRContractResolver : IContractResolver {      private readonly Assembly assembly;     private readonly IContractResolver camelCaseContractResolver;     private readonly IContractResolver defaultContractSerializer;      public SignalRContractResolver()     {         defaultContractSerializer = new DefaultContractResolver();         camelCaseContractResolver = new CamelCasePropertyNamesContractResolver();         assembly = typeof(Connection).Assembly;     }      public JsonContract ResolveContract(Type type)     {         if (type.Assembly.Equals(assembly))         {             return defaultContractSerializer.ResolveContract(type);          }          return camelCaseContractResolver.ResolveContract(type);     }  } 

Register it like

var settings = new JsonSerializerSettings(); settings.ContractResolver = new SignalRContractResolver(); var serializer = JsonSerializer.Create(settings); GlobalHost.DependencyResolver.Register(typeof (JsonSerializer), () => serializer); 

If you use a custom IoC you can run into problems because JsonSerializer is a concrete type and some IoCs like for example Ninject will inject unbound concrete types. In Ninjects case the solution is to register it with Ninject instead of with SignalRs own DependencyResolver

var settings = new JsonSerializerSettings(); settings.ContractResolver = new SignalRContractResolver(); var serializer = JsonSerializer.Create(settings); kernel.Bind<JsonSerializer>().ToConstant(serializer); 

More info on my blog: http://andersmalmgren.com/2014/02/27/why-overriding-jsonserializer-no-longer-work-in-signalr-2-0/

like image 68
Anders Avatar answered Sep 22 '22 01:09

Anders