Message Protocol Configuration
Learn to configure the message protocol.
We'll cover the following...
At the end of the AddSignalR
method call, you can replace the semicolon with the following block of code:
.AddJsonProtocol(options => {options.PayloadSerializerOptions.PropertyNamingPolicy = null;options.PayloadSerializerOptions.Encoder = null;options.PayloadSerializerOptions.IncludeFields = false;options.PayloadSerializerOptions.IgnoreReadOnlyFields = false;options.PayloadSerializerOptions.IgnoreReadOnlyProperties = false;options.PayloadSerializerOptions.MaxDepth = 0;options.PayloadSerializerOptions.NumberHandling = JsonNumberHandling.Strict;options.PayloadSerializerOptions.DictionaryKeyPolicy = null;options.PayloadSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.Never;options.PayloadSerializerOptions.PropertyNameCaseInsensitive = false;options.PayloadSerializerOptions.DefaultBufferSize = 32_768;options.PayloadSerializerOptions.ReadCommentHandling = System.Text.Json.JsonCommentHandling.Skip;options.PayloadSerializerOptions.ReferenceHandler = null;options.PayloadSerializerOptions.UnknownTypeHandling = JsonUnknownTypeHandling.JsonElement;options.PayloadSerializerOptions.WriteIndented = true;Console.WriteLine($"Number of default JSON converters: {options.PayloadSerializerOptions.Converters.Count}");});
Even though JSON protocol is enabled by default, using the AddJsonProtocol
method allows us to fine-tune it. Pretty much all of the settings are related to payload serialization. Let's cover what each of these settings does.
JSON message protocol settings
PropertyNamingPolicy
: This setting determines the policy of naming JSON properties. It usesJsonNamingPolicy
abstract class fromSystem.Text.Json
namespace. If you need to, you can create your own implementation of it by inheriting it from this class. Then, you can apply your own implementation to this setting.Encoder
: This property accepts any implementation of theJavaScriptEncoder
class fromSystem.Text.Encodings.Web
namespace. If your clients use any custom encoding in JSON data that they exchange with the server, you can override this class and apply the custom encoding rules in it.IncludeFields
: This option determines whether or not fields are handled during serialization and deserialization. Normally, just the C# properties of your data classes are handled. With this option set totrue
, fields will be handled too. ...