具有可空类型的REST?

我打了砖墙。 我的REST实现不接受Nullable值。

[OperationContract] [WebInvoke(ResponseFormat = WebMessageFormat.Json, UriTemplate = "/Transactions?AccNo={AccNo}&CostCentreNo={CostCentreNo}&TransactionType={TransactionType}&Outstanding={Outstanding}&CheckStartDate={CheckStartDate}&CheckEndDate={CheckEndDate}")] List GetTransactions(Int32 AccNo, Int32 CostCentreNo, Int32 TransactionType, Boolean Outstanding, DateTime? CheckStartDate, DateTime? CheckEndDate); 

而我原来的SOAP实现确实如此。 那么有办法解决这个问题吗? 或者我是否必须重新编写代码?

我仍然不明白为什么日期时间必须可以为空而无法设置为null。

UriTemplate查询值的变量必须具有可由QueryStringConverter转换的类型。 可空类型不是。

你可以包装参数并通过POST传递它;

 [DataContract(Name = "Details", Namespace = "")] public class Details { [DataMember] public Int32 AccNo; [DataMember] public Int32 CostCentreNo; [DataMember] public Int32 TransactionType; [DataMember] public Boolean Outstanding; [DataMember] public DateTime? CheckStartDate; [DataMember] public DateTime? CheckEndDate; public Details() {} } [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "/Transactions", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)] List GetTransactions(Details details); 

通常,您可以将日期作为字符串而不是DateTime传递,然后在接收端的字符串上使用DateTime.Parse()。

问题在于您正在尝试将查询字符串值转换为可空的,因为在真正的SOAP中,您的请求将是支持nullables的XML。

如果您坚定地保留方法的结构,并且CheckedDate确实是可选的,那么您应该将其更改为可选参数。

GetMethod(...., DateTime CheckStartDate = default(DateTime), DateTime CheckEndDate = default(DateTime))

然后,在您的方法中检查CheckedDate > DateTime.MinValue