如果我有这样的枚举:
[Flags]
public enum EyeColor {
All = 1,
Brown = 2,
Blue = 4,
Hazel = 8,
Green = 16
}
然后返回如下JSON结果:
jsonBody.EyeColor = EyeColor.Brown | EyeColor.Blue;
我在客户端的jsonBody中看到以下内容:
"Brown, Blue"
但是,如果我通过EyeColor属性将上述字符串发送到WebAPI:
var eyeColor = "Brown, Blue"
var query = '?Index=1&EyeColor=` + eyeColor;
// send json GET request and use [FromUri] to extract
服务器端,我得到:
dto.EyeColor: 0
尽管如果我这样做:
var eyeColor = "All"
var query = '?Index=1&EyeColor=` + eyeColor;
// send json GET request and use [FromUri] to extract
我得到
dto.EyeColor: All
因此,我想知道的是,如果我不仅想从WebApi中检索字符串序列化的枚举,还想发送一个字符串来表示已选择的多个枚举(并反序列化为多个枚举),我需要做什么?
我的Global.asax:
JsonSerializerSettings jSettings = new JsonSerializerSettings();
jSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = jSettings;
GlobalConfiguration.Configuration
.Formatters
.JsonFormatter
.SerializerSettings
.ContractResolver = new CamelCasePropertyNamesContractResolver();
我是个白痴。
"Brown,+Blue"
这就是我们所需要的。