You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

已配置JSON格式的WCF接口为什么期望接收text/xml而非application/json

问题原因

你在接口中通过WebInvoke特性声明了REST风格的JSON接口,但WCF默认配置使用基于SOAP协议的basicHttpBinding/basicHttpsBinding,仅支持text/xml类型的请求,没有配置适配REST请求的绑定和行为,因此收到application/json类型的请求时返回415媒体类型不支持错误。

解决步骤
    1. 修改web.config的system.serviceModel节点,添加REST接口需要的端点行为、绑定配置、服务端点声明:
<system.serviceModel>
  <behaviors>
    <serviceBehaviors>
      <behavior>
        <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
        <serviceDebug includeExceptionDetailInFaults="false"/>
      </behavior>
    </serviceBehaviors>
    <!-- 新增REST端点行为 -->
    <endpointBehaviors>
      <behavior name="restBehavior">
        <webHttp />
      </behavior>
    </endpointBehaviors>
  </behaviors>
  <bindings>
    <!-- 配置webHttp绑定支持JSON -->
    <webHttpBinding>
      <binding name="jsonBinding">
        <security mode="None" /> <!-- 本地HTTP调试用,HTTPS的话改成Transport -->
      </binding>
    </webHttpBinding>
  </bindings>
  <!-- 显式配置服务端点 -->
  <services>
    <service name="你的命名空间.Service1"> <!-- 注意替换成你Service1类的完整命名空间 -->
      <endpoint address="" 
                binding="webHttpBinding" 
                bindingConfiguration="jsonBinding" 
                contract="你的命名空间.IService1" <!-- 注意替换成你IService1接口的完整命名空间 -->
                behaviorConfiguration="restBehavior"/>
    </service>
  </services>
  <protocolMapping>
    <add binding="webHttpBinding" scheme="http" /> <!-- HTTP对应webHttpBinding -->
    <add binding="basicHttpsBinding" scheme="https" /> <!-- 需HTTPS的话也可以改成webHttpBinding并调整security配置 -->
  </protocolMapping>    
  <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
    1. 检查你的Service1.svc文件头部,确认添加了WebServiceHostFactory声明:
<%@ ServiceHost Language="C#" Debug="true" Service="你的命名空间.Service1" CodeBehind="Service1.svc.cs" Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>
    1. 重新编译启动项目,再次用Postman请求即可正常返回JSON格式的Hello World!响应。

内容的提问来源于stack exchange,提问作者blies

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 06:57:03