【问题标题】:WCF REST Service Pass object as parameter in POST methodWCF REST 服务传递对象作为 POST 方法中的参数
【发布时间】:2016-08-13 20:19:29
【问题描述】:

我的 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 用于ServerConnectionInfo。此外,在我的班级 ServerConnectionInfo 中,我有 stringint 数据成员。我为HttpWebRequest 正确设置了ContentTypeContentLength

此方法与 REST 客户端“POSTMAN”完美配合。

我错过了什么?

【问题讨论】:

  • 如何调用 REST WCF? HttpClient ?HttpWebRequest? RestSharp?
  • 我正在使用 HttpWebRequest

标签: c# wcf rest


【解决方案1】:

我刚刚在我的代码中更改了以下行(问题中未提及),它开始工作。

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

改为

request.ContentType = "application/json";

现在,我的疑问是,在请求的内容类型中指定字符集有什么问题。

【讨论】:

  • 应该是charset=utf-8: 字符是导致您的 400 的原因。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
  • 2012-07-03
相关资源
最近更新 更多