2

I have settings defined using enum in C# backend each with unique number.

public enum Settings
{
    Setting1 = 1,
    Setting2 = 2,

    //...
}

I send the settings to client using WebAPI in dictionary

public MyModel
{
    public Dictionary<Settings, string> MySettings { get; set; }

    //...other properties...
}

But the thing is I have this Enum defined in typescript as well and I want to refer to this using the enum.

The problem is WebAPI converts the enum to the string instead of a number. As the solution is quite large I don't want to remove the StringEnumConverter from configuration and just define the converter to number for this property only as well as preserve the type of the dictionary and not changing it to Dictionary<int, string>.

Is there a way, how to do this using attribute?

3
  • 2
    write a custom json converter and annotate your property using the custom converter Commented Aug 18, 2015 at 8:56
  • @entre I was wondering about an easier way, but as I see I might not avoid this option. Commented Aug 18, 2015 at 9:44
  • another way might be.. derive from string to enum converter and override can convert to return false if enum type is your enum else return base.canconvert... should be lesser change than earlier one Commented Aug 18, 2015 at 12:43

1 Answer 1

1

You could have a private/protected property that you can use the way you want. You could also make these standard get/set methods and have them be public.

public class MyModel
{
    public Dictionary<int, string> MySettings { get; set; }

    //One way of handling it.
    private Dictionary<Settings, string> MyBetterSettings
    {
        get { return MySettings.ToDictionary(setting => (Settings) setting.Key, setting => setting.Value); }
        set { MySettings = value.ToDictionary(setting => (int) setting.Key, setting => setting.Value); }
    }

    //Simple C# 6 methods
    public Dictionary<Settings, string> GetSettings => MySettings.ToDictionary(setting => (Settings) setting.Key, setting => setting.Value);
    public void SetSettings(Dictionary<Settings, string> settings) => MySettings = settings.ToDictionary(setting => (int)setting.Key, setting => setting.Value);
}

It's not the best, but it is a nice tradeoff for not having to worry about changing how it serializes.

Sign up to request clarification or add additional context in comments.

1 Comment

General serialization solution would be more elegant, but for my purpose it's just fine. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.