我有一个WCF服务,它将一个字符串值“name”作为参数。此服务界面如下所示......
[ServiceContract(Name = "ContactLookup", Namespace = "Search")]
public interface IAjaxResultSearcherService
{
[OperationContract]
[WebGet(RequestFormat = WebMessageFormat.Json)]
Result[] SearchResultsWithNameLike(string name);
}
使用以下配置公开服务...
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
<behaviors>
<serviceBehaviors>
<behavior name="AjaxServiceBehavior">
<serviceDebug
includeExceptionDetailInFaults="true"
httpHelpPageEnabled="true"/>
<serviceMetadata httpGetEnabled="true" httpGetUrl=""/>
<serviceCredentials>
<serviceCertificate findValue="localhost"
storeLocation="LocalMachine"
storeName="My" x509FindType="FindBySubjectName"/>
</serviceCredentials>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="JsonBehavior">
<enableWebScript/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name="HelloIndigo.AjaxResultSearcherService"
behaviorConfiguration="AjaxServiceBehavior">
<endpoint address="json"
binding="webHttpBinding"
behaviorConfiguration="JsonBehavior"
contract="Contract.IAjaxResultSearcherService" />
</service>
</services>
</system.serviceModel>
我的.svc文件使用WebScriptServiceHostFactory。这似乎有效,这意味着我可以从我的jquery客户端连接到服务,但即使我通过ajax调用设置参数值,当消息到达服务实现时,参数值为null。
我通过jquery调用服务,就像这样......
$.ajax({
url: url,
data: { "name":"test" },
type: "GET",
processData: false,
contentType: "application/json",
timeout: 10000,
dataType: "text",
success: function(res) {
alert('function successful! returned: ' + res.toString());
},
error: function(xhr) {
alert('an error occurred: ' + xhr.responseText);
}
});
我从服务调用中没有错误,但是当我调试进程时,参数值为null。为什么WCF不会像我期望的那样传递参数值?
感谢您的帮助。
答案 0 :(得分:1)
在我的试验中,我试图使用JSON.org的JSON2来“串化”我的json对象并将其作为数据对象传递给ajax调用,并将processData参数设置为false。一旦我决定将数据元素保留为本机JSON对象并将processData设置为true,我的参数值就会被填充。
我仍然不确定为什么JSON2.js的stringify没有使数据参数有效,但至少这是有效的。
所以,之前我有以下内容:
var json = JSON.stringify({ "name":"test" });
$.ajax({
url: url,
data: json,
type: "GET",
processData: false,
contentType: "application/json",
timeout: 10000,
dataType: "text",
success: function(res) {
alert('function successful! returned: ' + res.toString());
},
error: function(xhr) {
alert('an error occurred: ' + xhr.responseText);
}
});
工作版本看起来像这样......
var json = { "name":"test" };
$.ajax({
url: url,
data: json,
type: "GET",
processData: true,
contentType: "application/json",
timeout: 10000,
dataType: "text",
success: function(res) {
alert('function successful! returned: ' + res.toString());
},
error: function(xhr) {
alert('an error occurred: ' + xhr.responseText);
}
});