簡體   English   中英

WCF REST服務傳遞對象作為POST方法中的參數

[英]WCF REST Service Pass object as parameter in POST method

我的WCF服務中有一個方法。

[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 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 for ServerConnectionInfo 此外,我的類中ServerConnectionInfo ,我有stringint數據成員。 我正確地為HttpWebRequest設置ContentTypeContentLength

此方法與REST客戶端“ POSTMAN”完美配合。

我想念什么?

我只是改變了以下行(在這個問題沒有提及),在我的代碼,並開始工作。

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

變成

request.ContentType = "application/json";

現在,我的疑問是,在請求的內容類型中指定字符集有什么問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM