WCF REST服务JSON发布数据

Gro*_*ogh 11 c# rest wcf post json

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

提前致谢.

web.config中

<system.web>
  '<compilation debug="true" targetFramework="4.0" />
</system.web>

<system.webServer>
 <modules runAllManagedModulesForAllRequests="true">
   <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
 </modules>
</system.webServer>

<system.serviceModel>
 <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
 <standardEndpoints>
   <webHttpEndpoint>
     <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/>
   </webHttpEndpoint>
 </standardEndpoints>
</system.serviceModel>
Run Code Online (Sandbox Code Playgroud)

的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)));
      }
   }
Run Code Online (Sandbox Code Playgroud)

服务代码

[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;
   }
}
Run Code Online (Sandbox Code Playgroud)

提琴手请求标题

Host: localhost
Content-Length: 20
Content-Type: application/json; charset=UTF-8
Run Code Online (Sandbox Code Playgroud)

请求机构

{"Name":"Frank"}
Run Code Online (Sandbox Code Playgroud)

来自提琴手的原始回应

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: "
Run Code Online (Sandbox Code Playgroud)

Gro*_*ogh 20

偶然发现此链接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;
}
Run Code Online (Sandbox Code Playgroud)

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