我从ajax调用WCF服务,我可以将它作为GET请求而不是POST请求。所以:
[OperationContract]
[WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
public UserObject GetUser(string name)
{
// Add your operation implementation here
var uo = new UserObject() { CustClass = "Guest", fname = "Chris", Email = "chris@Something", IsMobile = false };
uo.fname = name;
return uo;
}
和
var json = { "name": "test" };
$.ajax({ //get user name and customer class
type: "GET",
url: "WritingAnalysisService.svc/GetUser",
data: json,
processData: true,
contentType: "application/json",
timeout: 10000,
dataType: "json",
cache: false,
success: function (data) { //get user name and customer class
customerclass = data.d.custclass;
ffname = data.d.fname;
}
});
工作但是:
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
public UserObject GetUser(string name)
{
// Add your operation implementation here
var uo = new UserObject() { CustClass = "Guest", fname = "Chris", Email = "chris@Something", IsMobile = false };
uo.fname = name;
return uo;
}
和
$.ajax({ //get user name and customer class
type: "POST",
url: "WritingAnalysisService.svc/GetUser",
data: json,
processData: true,
contentType: "application/json",
timeout: 10000,
dataType: "json",
cache: false,
success: function (data) { //get user name and customer class
customerclass = data.d.custclass;
ffname = data.d.fname;
}
});
没有。我错过了一些简单的事吗?我在这里撕扯我的头发。感谢
答案 0 :(得分:2)
使用
BodyStyle = WebMessageBodyStyle.WrappedRequest
for WebInvokeAttribute
答案 1 :(得分:1)
我有类似的示例项目。我在这里发布,希望有所帮助:
的Web.config:
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="WebFormApp.MyWcfServiceAspNetAjaxBehavior">
<enableWebScript/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<services>
<service name="WebFormApp.MyWcfService">
<endpoint address="" behaviorConfiguration="WebFormApp.MyWcfServiceAspNetAjaxBehavior" binding="webHttpBinding" contract="WebFormApp.MyWcfService"/>
</service>
</services>
</system.serviceModel>
WCF:
<ServiceContract(Namespace:="")> _
<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)> _
Public Class MyWcfService
<OperationContract(), _
WebInvoke(Method:="POST", _
BodyStyle:=WebMessageBodyStyle.WrappedRequest, _
ResponseFormat:=WebMessageFormat.Json)> _
Public Function GetTheEntity() As MyEntity
Return New MyEntity With {.Name = "TheName", .Family = "TheFamily"}
End Function
End Class
JS:
function doTestJQuery() {
$.ajax({
type: "POST",
url: "MyWcfService.svc/GetTheEntity",
data: null,
contentType: "application/json; charset=utf-8",
dataType: "json",
processdata: true,
success: srvSuccessJQuery,
error: null
});
}
function srvSuccessJQuery(result) {
alert(result.d.Family)
};