我开发了一个示例 WCF REST 服务,它接受创建一个“Order”对象,方法实现如下所示:
[Description("Updates an existing order")]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, UriTemplate = "/Orders")]
[OperationContract]
public void UpdateOrder(Order order)
{
try
{
using (var context = new ProductsDBEntities())
{
context.Orders.Attach(order);
context.ObjectStateManager.ChangeObjectState(order, System.Data.EntityState.Modified);
context.SaveChanges();
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.OK;
WebOperationContext.Current.OutgoingResponse.StatusDescription = "Order updated successfully.";
}
}
catch (Exception ex)
{
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.InternalServerError;
WebOperationContext.Current.OutgoingResponse.StatusDescription = ex.Message + " " + ((ex.InnerException != null) ? ex.InnerException.Message : string.Empty);
}
}
我正在尝试使用“WCF Rest Starter Kit”程序集在客户端中使用此服务。使用服务的客户端代码如下:
var order = new Order(){
OrderId = Convert.ToInt32(ddlCategories.SelectedItem.Value)
};
order.Order_X_Products.Add(new Order_X_Products { ProductId = 1, Quantity = 10});
order.Order_X_Products.Add(new Order_X_Products { ProductId = 2, Quantity = 10});
var content = HttpContentExtensions.CreateJsonDataContract<Order>(order);
var updateResponse = client.Post("Orders", content);
下面一行
var updateResponse = client.Post("Orders", content);
引发以下错误:
Server Error in '/' Application.
Specified argument was out of the range of valid values.
Parameter name: value
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: value
我有类似的逻辑来创建订单并且工作正常。
我还尝试删除以下行
order.Order_X_Products.Add(new Order_X_Products { ProductId = 1, Quantity = 10});
order.Order_X_Products.Add(new Order_X_Products { ProductId = 2, Quantity = 10});
但仍然是同样的错误。
请帮我解决这个问题。
我还尝试将 Order 对象序列化为 XML,并将 UpdateOrder 方法的 RequestFormat 更改为 XML。在这种情况下,如果填充了任何相关实体,我会收到以下错误。
Server Error in '/' Application.
Object graph for type 'WcfRestSample.Models.Common.Order_X_Products' contains cycles and cannot be serialized if reference tracking is disabled.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Runtime.Serialization.SerializationException: Object graph for type 'WcfRestSample.Models.Common.Order_X_Products' contains cycles and cannot be serialized if reference tracking is disabled.
Source Error:
Line 102:
Line 103: var content = HttpContentExtensions.CreateDataContract<Order> (order);
Line 104: var updateResponse = client.Post("Orders", content);
Line 105:
Line 106:
我想通过“Order_X_Products”映射表“更新”一个订单以及相关的“产品”。