2012-12-12 122 views
1

我用下面POST“操作”配置REST风格的WCF:宁静的WCF POST问题

[OperationContract] 
[WebInvoke(Method = "POST", UriTemplate = "/Test", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json)] 
void PostTest(Stream stream); 

在我的web.config中,我配置如下:

<service name="MyTest.TestSvc" behaviorConfiguration="MyTest.TestBehavior" > 
    <endpoint address="" behaviorConfiguration="MyBehavior" binding="webHttpBinding" contract="MyTest.ITestSvc"/> 
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> 
</service> 

<endpointBehaviors> 
    <behavior name="MyBehavior"> 
     <webHttp /> 
    </behavior> 
</endpointBehaviors> 

<serviceBehaviors> 
    <behavior name="MyTest.TestBehavior"> 
     <serviceMetadata httpGetEnabled="true" /> 
     <serviceDebug includeExceptionDetailInFaults="true" /> 
    </behavior> 
</serviceBehaviors> 

当我送使用“text/plain的” 一个POST消息“JSON”一切工作正常。 然而,当我尝试发送POST消息 的ContentType =“应用/ JSON” 它失败,出现以下消息: 远程服务器返回一个错误:(400)错误的请求

的我找到的唯一解决方案是定义Factory类:System.ServiceModel.Activation.WebServiceHostFactory int Svc定义标记。

我发现下面的链接此解决方案: Send JSON to WCF 3.5 using Ajax

我的理解,如果你不想编辑web.config定义WebServiceHostFactory才有用。

如何在不定义WebServiceHostFactory的情况下使其工作?

请注意,我成功获取“json”内容类型的POST消息,但未获取“application/json”内容类型。

回答

3

问题是,要使用原始编程模型(使用Stream参数),您需要告诉WCF不要试图将请求理解为JSON,而只是将原始请求主体传递给参数。你可以使用WebContentTypeMapper来做到这一点。 http://blogs.msdn.com/b/carlosfigueira/archive/2008/04/17/wcf-raw-programming-model-receiving-arbitrary-data.aspx的帖子显示了如何做到这一点。工厂解决方案的工作原理是因为它在创建端点时会这样做。