Selectively enable JsConfig.IncludeTypeInfo per class via an attribute?

I’ve been looking at the json-format docs, and not yet thinking of a way to do JsConfig.IncludeTypeInfo on a class-by-class basis via C# attribute… any chance this is something you could easily enable or sample code for how to accomplish with existing implementation?

I know we can currently do this via JsConfig<Type>.IncludeTypeInfo = true in AppHost.Configure method but it seems desirable from a locus of information standpoint to have this indicated with the class definition itself.

I’d be perfectly fine with the common approach of enumerating all types within assembly, filtering by attribute, and would then just need a runtime method like JsConfig.Init(type, new Config { IncludeTypeInfo = true })

The existing Js.CreateScope() facility seems very flexible, maybe I’m missing an opportunity there?

Thanks as always, discovering what ServiceStack already includes never ceases to amaze me.

There’s no runtime method that allows you to configure a runtime type with JsConfig.Init(type) so you would need to use reflection to set a property on the generic class JsConfig<Type>.IncludeTypeInfo=true, which is slow so I’d personally Customize JSON Responses in Service by returning results in a custom scope, e.g:

return new HttpResult(responseDto) {
    ResultScope = () => 
        JsConfig.With(new Config { IncludeTypeInfo = true })
};

To make it declarative I would use a custom attribute or use the existing [Meta(name,value)] attribute to specify the scope, e.g:

[Meta(nameof(JsConfig), nameof(JsConfigScope.IncludeTypeInfo))]
public class MyResponseDto {...}

That either an extension method like dto.ToResult() or the OnAfterExecute Service Filter check if the Response DTO has the attribute and if it does to return it within that custom scope, e.g:

var attr = responseDto.GetType().AllAttributes<MetaAttribute>()
    .FirstOrDefault(x => x.Name == nameof(JsConfig));
return attr != null
    ? new HttpResult(responseDto) {
            ResultScope = () => 
                JsConfig.CreateScope(attr.Value)
        }
    : responseDto;
1 Like