我正在尝试使用POST方法调用WCF REST服务。
[OperationContract]
[AllowCrossSiteJson]
[WebInvoke(UriTemplate = "/PerformAction",
Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
[FaultContract(typeof(CpiFaultContract))]
string PerformAction(ActionMetaData data);
如果我使用以下C#代码,我可以正确调用该服务:
var serializer = new JavaScriptSerializer();
var jsonRequestString = serializer.Serialize(credentail);
var bytes = Encoding.UTF8.GetBytes(jsonRequestString);
// Initiate the HttpWebRequest with session support with CookiedFactory
var request = CreateHttpWebRequest("http://aviary.cloudapp.net/PerformAction");
request.Method = "POST";
request.ContentType = "application/json";
request.Accept = "application/json";
// Send the json data to the Rest service
var postStream = request.GetRequestStream();
postStream.Write(bytes, 0, bytes.Length);
postStream.Close();
// Get the login status from the service
var response = (HttpWebResponse)request.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
var jsonResponseString = reader.ReadToEnd();
以下是我正在使用的web.config
:
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="AviaryEndPointBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="AviaryServiceBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint name="" helpEnabled="true" defaultOutgoingResponseFormat="Xml"
automaticFormatSelectionEnabled="true"></standardEndpoint>
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="UrlRoutingModule"
type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</modules>
<handlers>
<add name="UrlRoutingHandler" preCondition="integratedMode" verb="*"
path="UrlRouting.axd"
type="System.Web.HttpForbiddenHandler, System.Web, Version=4.0.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</handlers>
</system.webServer>
</configuration>
但是,如果我使用以下Ajax方法,我什么也得不到,并且服务没有命中:
postData.JobActionList = JSON.stringify(jobActionLists);
var postDataString = JSON.stringify(postData);
jQuery.ajax({
url: "http://myService.cloudapp.net/PerformAction",
type: "POST",
data: postDataString,
contentType: "application/json; charset=utf-8",
success: function (result) {
alert("Success" + result.d);
},
error: function (req, status, error) {
alert('Service Failed : ' + req + ", " + status + ", " + error);
}
});
答案 0 :(得分:1)
快速建议:您是否正在对服务进行跨域调用?我有同样的问题,但切换到JSONP而不是JSON。 看看这篇文章:http://bendewey.wordpress.com/2009/11/24/using-jsonp-with-wcf-and-jquery/
答案 1 :(得分:0)
而是将Object值作为json发送到变量中作为pass并添加跨浏览器支持。
function updateExample() {
var myJSONData = '{"LastUpdatedBy":null,"DateUpdated":null,"CreatedBy":null,"DateCreated":null,"Description":null,"VideoID":' + videoId + ',"CommentID":null,"UserID":"' + userId + '","UserName":"' + document.getElementById('txtUserName').value + '","CommentText":"' + document.getElementById('txtComment').value + '","Location":846.728,"ParentCommentID":null}';
jQuery.support.cors = true;
$.ajax({
type: "POST",
url: "http://myService.cloudapp.net/PerformAction",
contentType: "application/json; charset=utf-8",
data: myJSONData,
dataType: "jsonp",
async: false,
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, status, jqXHR) {
alert('success');
},
error: function () {
alert('failed');
},
});
}