1

I am trying to call WCF REST service with POST method.

[OperationContract]
[AllowCrossSiteJson]
[WebInvoke(UriTemplate = "/PerformAction", 
                Method = "POST", 
         RequestFormat = WebMessageFormat.Json, 
        ResponseFormat = WebMessageFormat.Json)]
[FaultContract(typeof(CpiFaultContract))]
string PerformAction(ActionMetaData data);

If I use the following C# code I am able to call the service correctly:

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();

Following is the web.config I am using:

<?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>

However if I use the following Ajax Method I get nothing and there is no hit on the service:

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);
    }
});
4

2 回答 2

1

快速建议:您是否正在对服务进行跨域调用?我有同样的问题,但切换到 JSONP 而不是 JSON。看看这篇文章:http ://bendewey.wordpress.com/2009/11/24/using-jsonp-with-wcf-and-jquery/

于 2012-06-15T11:12:47.283 回答
0

而是将 Object 值作为 json 在变量中作为传递发送并添加跨浏览器支持。

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');
    },

});

}

于 2014-08-28T07:23:28.333 回答