问题
I've hit a brickwall. My REST implementation won't accept Nullable values.
[OperationContract]
[WebInvoke(ResponseFormat = WebMessageFormat.Json, UriTemplate = "/Transactions?AccNo={AccNo}&CostCentreNo={CostCentreNo}&TransactionType={TransactionType}&Outstanding={Outstanding}&CheckStartDate={CheckStartDate}&CheckEndDate={CheckEndDate}")]
List<Transactions> GetTransactions(Int32 AccNo, Int32 CostCentreNo, Int32 TransactionType, Boolean Outstanding, DateTime? CheckStartDate, DateTime? CheckEndDate);
Whereas my original SOAP implementation does. So is there a way around this? Or do I have to re-write my code?
I still don't quite get why a datetime must be nullable anyway to be set to null.
回答1:
Variables for UriTemplate query values must have types that can be converted by QueryStringConverter. Nullable types is not.
You could wrap the parameters and pass it through POST as such;
[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<Transactions> GetTransactions(Details details);
Opionally, you could pass the date as strings instead of DateTime, and then use DateTime.Parse() on the string on the receiving end.
回答2:
The problem is in that you are trying to convert a query string value to a nullable, as in a true SOAP your request would be XML which does support nullables.
If you are firm on preserving the structure of your method, and CheckedDate is indeed optional, then you should change it to be an optional parameter.
GetMethod(...., DateTime CheckStartDate = default(DateTime), DateTime CheckEndDate = default(DateTime))
and then, in your method check for CheckedDate > DateTime.MinValue
来源:https://stackoverflow.com/questions/7646027/rest-with-nullable-types