【问题标题】:Restful WCF POST issue with application/json content type request应用程序/json内容类型请求的Restful WCF POST问题
【发布时间】:2012-11-30 04:50:55
【问题描述】:

我已经使用以下 POST“操作”配置了一个 RESTful WCF:

[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""json" 发送 POST 消息时,一切正常。 但是,当我尝试发送 POST 消息时 ContentType = "应用程序/json" 它失败并显示以下消息: 远程服务器返回错误:(400) Bad Request

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

我在以下链接中找到了此解决方案: Send JSON to WCF 3.5 using Ajax

据我了解,仅当您不想编辑 web.config 时,定义 WebServiceHostFactory 才有用。

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

请注意,我成功获得了“json”内容类型的 POST 消息,但没有获得“application/json”内容类型。

【问题讨论】:

    标签: json wcf post wcf-rest bad-request


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2013-05-25
      • 1970-01-01
      • 1970-01-01
      • 2018-09-03
      • 2015-09-07
      • 1970-01-01
      • 2018-01-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多