我在我的WCF服務中有一個方法。WCF REST服務傳遞對象作爲POST方法中的參數
[OperationContract]
[FaultContract(typeof(Hitachi.WebServices.Common.WebServiceFaultException))]
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "Syslog/AddServerConfiguration")]
void AddServerConfiguration(ServerConnectionInfo serverConnectionInfo);
從客戶端,我使用`HttpWebRequest``。我一直在收到「遠程服務器返回錯誤:(400)錯誤的請求。」
傳遞參數serverConnectionInfo,我嘗試不同的選擇 -
[1]使用簡單的String格式化 -
String body = string.Format("{{\"serverConnectionInfo\":{{\"DeviceIP\":\"{0}\",\"Password\":\"{1}\",\"Port\":0,\"UserName\":\"{2}\"}}}}", ipAddress, password, userName);
if (!String.IsNullOrEmpty(body))
{
byte[] bodyBytes = Encoding.UTF8.GetBytes(body);
request.GetRequestStream().Write(bodyBytes, 0, bodyBytes.Length);
request.GetRequestStream().Close();
}
[2]使用JavaScriptSerializer
-
JavaScriptSerializer jss = new JavaScriptSerializer();
string data = jss.Serialize(connInfo);
String body = string.Format("{{\"serverConnectionInfo\":{0}}}", data);
[3]使用JsonConvert
-
string body = JsonConvert.SerializeObject(new { serverConnectionInfo = connInfo });
request.ContentLength = body.Length;
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(body);
writer.Close();
[4]使用DataContractJsonSerializer
。
我想指出,我使用DataContract
代替ServerConnectionInfo
。而且,在我的班級ServerConnectionInfo
裏面,我有string
和int
數據成員。我正確設置ContentType
和ContentLength
爲HttpWebRequest
。
此方法與REST客戶端「POSTMAN」完美兼容。
我錯過了什麼?
如何調用REST WCF? HttpClient?HttpWebRequest? RestSharp? – Mate
我使用的是HttpWebRequest – user1748546