Serializing Enums in ASP.NET SignalR

Was working on a new layered architecture sample that uses ASP.NET SignalR and found out that it couldn't serialize the enums properly by default.


As you can see from the screenshot, the LeaveStatuses enum has been serialized as a byte value instead of the text value. A quick solution will be to decorate the Status property with the [JsonConverter(typeof(StringEnumConverter))] attribute in the Leave entity class but I was reluctant to have my entities hard-coding that.

Fortunately, the problem can be easily solved with an alternative by including the following lines of code in the Startup class.

public class Startup
{
    
public void Configuration(IAppBuilder app)
    {
        
// Create JsonSerializer with StringEnumConverter.
        
var serializer = new JsonSerializer();
        
serializer.Converters.Add(new StringEnumConverter());
    
        
// Register the serializer.
        
GlobalHost.DependencyResolver.Register(typeof(JsonSerializer), () => serializer);

        app.MapSignalR();
    }
}

With that piece of code, the enums can now be serialized to their text values and I don't have to modify the properties in the entities.

No comments:

Post a Comment

Popular Post