应用程序/json内容类型请求的Restful WCF POST问题

Posted

技术标签:

【中文标题】应用程序/json内容类型请求的Restful WCF POST问题【英文标题】:Restful WCF POST issue with application/json content type request 【发布时间】: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”内容类型。

【问题讨论】:

【参考方案1】:

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

【讨论】:

以上是关于应用程序/json内容类型请求的Restful WCF POST问题的主要内容,如果未能解决你的问题,请参考以下文章

如何在java中发送具有不同内容类型的mime multipart restful请求

vue中的axios.post使用json数据传输,出现请求头字段内容类型是不被允许的情况的解决方案

Android 向 WCF RESTful WS 发布请求(JSON 参数)

无法解析请求正文。确保请求正文与指定的内容类型匹配:应用程序/json [重复]

http请求/restful/序列化反序列化/JSON

Flask-restful:如何只响应附带的请求('Accept':'application/json')?