出於某種原因,我的AttributeContract對象沒有從我的客戶端正確傳遞到我的服務方法。我可以通過調用成功訪問方法,但對象是空的。任何建議我在做什麼錯在這裏?WCF REST Post Post Complex對象
客戶
using (var client = new HttpClient())
{
string serviceCall = string.Format("{0}AttributeService.svc/AttributeDefinition/", _serviceLocation);
int attributeIdInt = Convert.ToInt32(attributeId);
int objectIdInt = Convert.ToInt32(objectId);
AttributeContract attributeContract = new AttributeContract()
{
AttributeId = attributeIdInt,
AttributeValue = attributeValue,
ObjectId = objectIdInt,
ObjectType = objectType
};
string attributeString = JsonConvert.SerializeObject(attributeContract);
string requestJsonString = "{ \"attribute\" : " + attributeString + " }";
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, serviceCall);
request.Content = new StringContent(requestJsonString, Encoding.UTF8, "application/json");
HttpResponseMessage response = client.SendAsync(request).Result;
}
數據合同
[DataContract(Name = "AttributeContract")]
public class AttributeContract
{
[DataMember(Name = "AttributeId")]
public int AttributeId { get; set; }
[DataMember(Name = "Attribute")]
public string Attribute { get; set; }
[DataMember(Name = "AttributeValue")]
public string AttributeValue { get; set; }
[DataMember(Name = "ObjectId")]
public int ObjectId { get; set; }
[DataMember(Name = "ObjectType")]
public string ObjectType { get; set; }
[DataMember(Name = "LastModifiedDate")]
public DateTime LastModifiedDate { get; set; }
[DataMember(Name = "LastModifiedUser")]
public string LastModifiedUser { get; set; }
}
服務合同
[OperationContract]
[WebInvoke(Method = "PUT",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "AttributeDefinition/")]
void UpdateAttributes(AttributeContract attribute);
服務方法
[OperationBehavior(TransactionScopeRequired = true)]
public void UpdateAttributes(AttributeContract attribute)
{
attribute.LastModifiedDate = DateTime.Now;
}
是的 - 該方法是一個錯誤,它已被糾正,並具有相同的結果。 哪些對象名稱需要相同。 JSON中的對象名稱和服務合約,服務方法...? 我試過幾種不同的命名約定,因爲這似乎是最明顯的問題。 – crowemi
這不重要,不要使用對象名稱或方法變量名稱。僅發送屬性:{AttributeId:1,Attribute:「ss」} – mkysoft
首先使用工具而不是c#代碼進行服務測試。例如Chrome瀏覽器有一個名字是Postman的擴展名是最好的。 – mkysoft