1

寻找某种方法在 WCF restful 服务中创建一个 post 方法,它可以接受 xml 和 json。我可以看到 Get 方法可以根据请求标头自动返回 json/xml。

我能想到的一种解决方案是:

  1. 将帖子数据获取为“Stream”并将其读取为字符串。
  2. 检查请求标头并将其反序列化为 json 或 xml。
  3. 相应地设置 OutgoingResponse 格式并返回响应。

我能够做到#1,但卡在#2 和#3。

4

1 回答 1

1

微软已经为你做了这件事,不要重新发明轮子。

public class DataController : ApiController
{
    public void Post(DataModel model)
    {
        // Whether the body contains XML, JSON, or Url-form-encoded it will be deserialized
        // into the model object which you can then interact with in a strongly-typed manner
    }
}

public class DataModel
{
    public string PropertyA { get; set; }
    public string PropertyB { get; set; }
}

您可以免费下载包含新 Web API 的 ASP.NET MVC4。http://www.asp.net/mvc/mvc4。这基本上是 WCF Web API 的最终产品,不再受支持。除非您已经使用原始 Web API 编写了太多代码以至于无法进行切换,否则从长远来看,这将为您节省大量时间。否则,您将被困在具有永远无法修复的错误的 Beta 产品中。

于 2012-08-26T07:29:20.743 回答