我使用以下 post 方法开发了一个 WCF 服务:
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "/InsertBearingData")]
bool InsertBearingData(String JSONString);
我正在使用 Fiddler 为该方法制定 HTTP POST 请求,但它返回 Status Code - 400 Bad Request
。这是提出的要求:
请求 header :
Host: localhost:21468
Content-Length: 96
Content-Type: application/json
请求正文:
[{"start time":"29-03-2013 11:20:11.340","direction":"SW","end time":"29-03-2013 11:20:14.770"}]
能否请您告诉我如何制定一个好的请求以获得成功的响应?
最佳答案
您的代码中存在一些问题:
- 参数的数据类型是字符串,但你传递的是一个JSON数组;字符串参数需要传递 JSON 字符串。
- 操作的正文样式设置为
Wrapped
,这意味着参数应该包装在一个对象中,该对象的键是参数名称,类似于{"JSONString":<the actual parameter value>}
。
要接收与您发送的请求类似的请求,您需要执行如下操作:
[ServiceContract]
public interface ITest
{
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "/InsertBearingData")]
bool InsertBearingData(MyType[] param);
}
[DataContract]
public class MyType
{
[DataMember(Name = "start time")]
public string StartTime { get; set; }
[DataMember(Name = "end time")]
public string EndTime { get; set; }
[DataMember(Name = "direction")]
public string Direction { get; set; }
}
关于WCF RESTful 服务 - HTTP POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15704537/