WCF请求:"传入的消息具有意外的消息格式' Raw'。该操作的预期消息格式是' Xml&#39 ;; '的Json'"

时间:2014-08-15 11:11:10

标签: c# asp.net ajax json wcf

我尝试使用AJAX从ASPX页面调用WCF服务。

我收到错误:“传入的消息有一个意外的消息格式'Raw'。操作的预期消息格式是'Xml';'Json'。这可能是因为没有在绑定上配置WebContentTypeMapper有关更多详细信息,请参阅WebContentTypeMapper的文档。“

代码如下。 (没有参数请求调用成功!)

服务方式:

[OperationContract]
[System.ServiceModel.Web.WebInvoke(Method = "POST",
   RequestFormat = WebMessageFormat.Json,
   ResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json)]
string SimpleRequest(string fullname);

的Web.config:

<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<behaviors>
  <serviceBehaviors>
    <behavior name="ServiceBehavior">
      <serviceMetadata httpGetEnabled="true"/>
      <serviceDebug includeExceptionDetailInFaults="true"/>
    </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
    <behavior name="ServiceAspNetAjaxBehavior">
      <enableWebScript />
    </behavior>
  </endpointBehaviors>
</behaviors>
<services>
  <service behaviorConfiguration="ServiceBehavior" name="GenesysService.GenesysService">
    <endpoint address=""
 binding="webHttpBinding"
 contract="GenesysService.IGenesysService"
  behaviorConfiguration="ServiceAspNetAjaxBehavior"> 
<identity>
        <dns value="localhost"/>
      </identity>
    </endpoint>
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
  </service>
</services>
<serviceHostingEnvironment 
 multipleSiteBindingsEnabled="true"
aspNetCompatibilityEnabled="true" />
<standardEndpoints>
  <webScriptEndpoint>
    <standardEndpoint name="" crossDomainScriptAccessEnabled="true" />
  </webScriptEndpoint>
</standardEndpoints>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<directoryBrowse enabled="true"/>
<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*"/>
    <add name="Access-Control-Allow-Methods" value="GET, POST"/>
  </customHeaders>
</httpProtocol>
</system.webServer>
</configuration>`

AJAX请求:

$.ajax({
type: "POST",
url: 'http://localhost:56428/GenesysService.svc/SimpleRequest',
data: JSON.stringify({fullname: "fullname"}),
dataType: "json",
crossDomain: true,
success: function (response) {
    alert('success!');
    alert(response);
},
error: function (xhr, ajaxOptions, thrownError) {
    alert('error!');
    alert(xhr.responseText);
}
});

我找到了相同的mistake。但后来我添加了下一个字符串:

contentType: "application/json"

我收到错误:“选项&lt; ...&gt; 405(方法不允许) XMLHttpRequest无法加载&lt; ...&gt;。无效的HTTP状态代码405“

1 个答案:

答案 0 :(得分:0)

Ajax调用中的Method Not Allowed响应是由于Javascript单一来源策略:

http://en.wikipedia.org/wiki/Same-origin_policy

要从您的页面调用服务,它需要位于相同的端口和协议上,或者您可以使用JSONP。

更多信息: http://www.sitepoint.com/jsonp-examples/