【问题标题】:WCF RESTful Service - HTTP POST RequestWCF RESTful 服务 - HTTP POST 请求
【发布时间】:2013-03-29 13:45:00
【问题描述】:

我使用以下发布方法开发了一个 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。这是制定的要求:

请求标头:

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"}]

您能告诉我如何制定一个好的请求以获得成功的响应吗?

【问题讨论】:

  • 您如何托管服务?请求的 URI 是什么?
  • 我刚刚在 Visual Studio 中运行。 URI 是:localhost:21468/DBService.svc/InsertBearingData
  • 您说I'm using Fiddler to formulate an HTTP POST - 您在 Fiddler 上使用了哪个 URL? Visual Studio 中的项目类型是什么(即你在运行什么)?
  • 它是一个 WCF 服务应用程序。 Fiddler中使用的URI是:localhost:21468/DBService.svc/InsertBearingData

标签: wcf http-post httprequest fiddler


【解决方案1】:

您的代码中存在一些问题:

  • 参数的数据类型是字符串,但是你传递的是一个JSON数组给它;字符串参数需要传递 JSON 字符串。
  • 操作的主体样式设置为Wrapped,这意味着参数应该包裹在一个key为参数名称的对象中,类似于{"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; }
}

【讨论】:

  • 非常感谢您的帮助。最后一个问题:如果我发送一个包含多个记录的数组,我将如何在方法 InsertBearingData 中遍历它
  • 对不起,我的代码有一个错误——操作参数类型应该是MyTypearray,因为输入是一个JSON数组。我编辑了帖子以更正它。
  • 非常感谢。我已经想通了。我做了一个List<MyType> 而不是一个数组,它也可以工作
猜你喜欢
  • 2011-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-11
  • 2011-09-30
  • 1970-01-01
  • 2013-01-30
  • 1970-01-01
相关资源
最近更新 更多