WCF支持使用在UriTemplate
內使用FlagsAttribute
作爲參數標記的枚舉類型。就像這樣:RESTful WCF服務中標誌枚舉的默認值
[DataContract]
[Flags]
public enum OptionsEnum
{
[EnumMember]
None = 0,
[EnumMember]
MyOption1 = 1,
[EnumMember]
MyOption2 = 2,
[EnumMember]
MyOption3 = 4,
[EnumMember]
MyOption4 = 8
}
[ServiceContract]
public interface MyServiceContract
{
[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "resource?options={options}")]
void MyOperation(OptionsEnum options);
}
資源就可以通過URL請求是這樣的:
GET /resource?options=None
GET /resource?options=MyOption1
GET /resource?options=MyOption1,MyOption3
所有這些作品真的很好,只要網址實際上包含options
參數的值。但是,如果我要求的資源,而不在URL中指定的值,如:
GET /resource
我得到的消息值異常不能爲空\ r \ n參數名:價值 和以下堆棧跟蹤:
at System.Enum.TryParseEnum(Type enumType, String value, Boolean ignoreCase, EnumResult& parseResult)
at System.Enum.Parse(Type enumType, String value, Boolean ignoreCase)
at System.ServiceModel.Dispatcher.QueryStringConverter.ConvertStringToValue(String parameter, Type parameterType)
at System.ServiceModel.Dispatcher.UriTemplateDispatchFormatter.DeserializeRequest(Message message, Object[] parameters)
at System.ServiceModel.Dispatcher.DispatchOperationRuntime.DeserializeInputs(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)
顯然,這是因爲QueryStringConverter
在這種情況下通過null
成Enum.Parse(...)
。因此MyServiceContract
的執行將不會執行。
當然,我可以切換到string
作爲options
參數的類型,並在服務實現中自己完成所有解析工作,但這不是我想要的,真的。
有誰知道一個乾淨的解決方案已經OptionsEnum.None
傳遞到服務實現,如果網址不包含值(就像0
傳遞類型int
的省略參數)?
我已經嘗試使用自定義TypeConverter
實現,但即使這似乎並不奏效。看看QueryStringConverter
的實現,它似乎總是試圖自行轉換enum
類型。