WCF REST服务不接受.Net 4中的JSON

时间:2011-02-15 16:12:01

标签: .net wcf json

我一直在尝试作为.Net 4的一部分引入的StandardEndpoints,我遇到了最奇怪的错误。

我的代码

[ServiceContract]
public interface IAuthenticator
{
    [OperationContract]
    [WebInvoke(UriTemplate = "AuthenticateUser", Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)]
    AuthPacket AuthenticateUser(string Username, string Password, string DeviceId);
}

我的web.config

  

<system.web>
  <compilation debug="true" targetFramework="4.0" />
</system.web>

<system.webServer>
  <modules runAllManagedModulesForAllRequests="true">
  </modules>
</system.webServer>

<system.serviceModel>
  <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
  <standardEndpoints>
    <webHttpEndpoint>
      <!--
          Configure the WCF REST service base address via the global.asax.cs file and the default endpoint
          via the attributes on the <standardEndpoint> element below
      -->
      <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/>
    </webHttpEndpoint>
  </standardEndpoints>
</system.serviceModel>

让我疯狂的例外!

415 Cannot process the message because the content type 'application/json' was not 
the expected type 'text/xml; charset=utf-8'.

我可以通过回到声明每项服务的.Net 3.5标准来解决这个问题,但是,除非我弄错了,WCF与.Net 4的主要升级之一是能够处理这样的事情。我做错了吗?

1 个答案:

答案 0 :(得分:6)

如果我正确阅读了此操作合同,您已将JSON定义为响应格式 - 但不是请求格式:

[ServiceContract]
public interface IAuthenticator
{
    [OperationContract]
    [WebInvoke(UriTemplate = "AuthenticateUser", Method = "POST", 
     BodyStyle = WebMessageBodyStyle.WrappedRequest, 
     ResponseFormat = WebMessageFormat.Json)]
    AuthPacket AuthenticateUser(string Username, string Password, string DeviceId);
}

这可能是问题吗?如果将RequestFormat = WebMessageFormat.Json添加到操作合同中会发生什么?

[ServiceContract]
public interface IAuthenticator
{
    [OperationContract]
    [WebInvoke(UriTemplate = "AuthenticateUser", Method = "POST", 
     BodyStyle = WebMessageBodyStyle.WrappedRequest, 
     RequestFormat = WebMessageFormat.Json,   <== ADD THIS HERE TO YOUR CODE !
     ResponseFormat = WebMessageFormat.Json)]
    AuthPacket AuthenticateUser(string Username, string Password, string DeviceId);
}

更新:如果您“开箱即用”WCF 4,其协议映射会将http://方案与basicHttpBinding相关联。

要解决此问题,您需要覆盖这样的默认协议映射(在您的web.config中):

默认协议映射

这个问题的答案很简单。 WCF定义传输协议方案(例如,http,net.tcp,net.pipe等)与内置WCF绑定之间的默认协议映射。默认协议映射可在.NET 4 machine.config.comments文件中找到,它看起来像这样:

<system.serviceModel>
   <protocolMapping>
       <add scheme="http" binding="webHttpBinding" bindingConfiguration="" />
   </protocolMapping>

现在,默认情况下http://.....会映射到webHttpBinding

(取自:A Developer's Introduction to Windows Communication Foundation 4