WCF REST服务JSON发布数据

寻找有关wcf 4rest服务的一些指导,该服务基于VS2010中的WCF REST模板40(CS)扩展。 我花了最近几天试图让这个bug工作,审查其他post,而我已经接近,我似乎无法越过终点线。 经过多次挫折之后,终于点击了服务并发布了(使用fiddler请求构建器),但是方法参数是空的,但它在请求构建器中正确设置。 我猜这可能是配置问题,但随着截止日期的临近,我没有时间进行更多的研究。 FWIW,在调试中,jsonstring变量为null。 自我肯定是一个noob问题,因为这是第一次通过REST为我,任何帮助将不胜感激!

提前致谢。

web.config中

 '               

的global.asax.cs

  public class Global : HttpApplication { void Application_Start(object sender, EventArgs e) { RegisterRoutes(); } private void RegisterRoutes() { RouteTable.Routes.Add(new ServiceRoute("Scoring", new WebServiceHostFactory(), typeof(ScoringSvc))); } } 

服务代码

 [ServiceContract] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] public class ScoringSvc { [OperationContract] [WebInvoke (Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat=WebMessageFormat.Json, ResponseFormat=WebMessageFormat.Json)] public string BOB(string jsonstring) { return "Received: " + jsonstring; } } 

Fiddler请求标题

 Host: localhost Content-Length: 20 Content-Type: application/json; charset=UTF-8 

请求机构

 {"Name":"Frank"} 

来自提琴手的原始回应

 HTTP/1.1 200 OK Cache-Control: private Content-Length: 12 Content-Type: application/json; charset=utf-8 Server: Microsoft-IIS/7.5 X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET Date: Mon, 21 Mar 2011 21:31:14 GMT "Received: " 

偶然发现此链接WCF + REST:请求数据在哪里? 并看到Glenn对将流传递给方法的响应,然后用流读取器将其拆分为字符串以获取表单发布数据。

修改原型服务代码如下

 [OperationContract] [WebInvoke (UriTemplate="/BOB", Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest)] public string BOB (Stream streamdata) { StreamReader reader = new StreamReader(streamdata); string res = reader.ReadToEnd(); reader.Close(); reader.Dispose(); return "Received: " + res; } 

这似乎可以解决问题,完整的json数组在流中传递,读入本地字符串,然后我可以使用json.net对其进行攻击,以序列化到字典中或从字典中传递到业务逻辑。 不是很漂亮,但function齐全。

我使用这个并且工作:

 [WebInvoke(ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest, Method = "POST", UriTemplate = "setExpositions?shelfId={shelfId}")] [OperationContract] public bool SetExpositions(int shelfId, List expositions) { } 

其中shelfId在GET中传递,并且展示在消息体中作为JSON数据传递。

您是否尝试在请求正文中输入{“jsonstring”:“Frank”}(在fiddler的Request Builder中)?

我认为在BodyStyle = WebMessageBodyStyle.WrappedRequest可能存在一个问题,我认为,尽管文档完全不清楚,但期望元素用方法名称包装。

设置解包,并将请求体设置为'{"Name":"Frank"}' (注意它周围的单引号。你实际上发布了一个包含JSON的字符串。我不知道为什么你会想要这个。它让我想起http://thedailywtf.com/Articles/XMLd-XML.aspx ,他们把xml放在他们的xml中。你把JSON放在你的JSON中。

您是否尝试过[WebGet(UriTemplate = ..)属性而不是post来查看是否可行?以下是一个示例 – http://blogs.msdn.com/b/kaevans/archive/2007/09/04 /creating-a-json-service-with-webget-and-wcf-3-5.aspx