已配置JSON格式的WCF接口为什么期望接收text/xml而非application/json
问题原因
你在接口中通过WebInvoke特性声明了REST风格的JSON接口,但WCF默认配置使用基于SOAP协议的basicHttpBinding/basicHttpsBinding,仅支持text/xml类型的请求,没有配置适配REST请求的绑定和行为,因此收到application/json类型的请求时返回415媒体类型不支持错误。
解决步骤
- 修改
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>
- 检查你的Service1.svc文件头部,确认添加了WebServiceHostFactory声明:
<%@ ServiceHost Language="C#" Debug="true" Service="你的命名空间.Service1" CodeBehind="Service1.svc.cs" Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>
- 重新编译启动项目,再次用Postman请求即可正常返回JSON格式的
Hello World!响应。
- 重新编译启动项目,再次用Postman请求即可正常返回JSON格式的
内容的提问来源于stack exchange,提问作者blies
相关产品推荐
相关产品推荐

