2016-04-20 134 views
0

我在我的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裏面,我有stringint數據成員。我正確設置ContentTypeContentLengthHttpWebRequest

此方法與REST客戶端「POSTMAN」完美兼容。

我錯過了什麼?

+0

如何調用REST WCF? HttpClient?HttpWebRequest? RestSharp? – Mate

+0

我使用的是HttpWebRequest – user1748546

回答

0

我剛剛在我的代碼中更改了以下行(未在問題中提及),並開始工作。

request.ContentType = "application/json; charset:utf-8"; 

改爲

request.ContentType = "application/json"; 

現在,我的疑問是,什麼是錯的,在內容類型的請求指定字符集。

+0

它應該是'charset = utf-8'。 ':'字符是什麼導致你的400。 –

相關問題