【发布时间】:2014-10-09 03:07:25
【问题描述】:
我尝试使用 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"
我收到错误:“OPTIONS <...> 405(不允许的方法) XMLHttpRequest 无法加载 <...>。无效的 HTTP 状态码 405"
【问题讨论】:
-
不需要“RequestFormat = WebMessageFormat.Json”和 JSON.stringify(