WCF REST服务传递对象作为POST方法中的参数
问题描述:
我在我的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”完美兼容。
我错过了什么?
答
我刚刚在我的代码中更改了以下行(未在问题中提及),并开始工作。
request.ContentType = "application/json; charset:utf-8";
改为
request.ContentType = "application/json";
现在,我的疑问是,什么是错的,在内容类型的请求指定字符集。
+0
它应该是'charset = utf-8'。 ':'字符是什么导致你的400。 –
如何调用REST WCF? HttpClient?HttpWebRequest? RestSharp? – Mate
我使用的是HttpWebRequest – user1748546