【问题标题】:Unable to Call WCF REST Service from Jquery无法从 Jquery 调用 WCF REST 服务
【发布时间】:2012-06-15 11:01:19
【问题描述】:

我正在尝试使用 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);
    }
});

【问题讨论】:

  • 您好,您能否发布您的错误代码。你得到的 HTTP 响应是什么
  • 你能发布你指定的路由条目吗?
  • 实际上,如果我发送没有数据的请求,那么它会到达服务端点。但如果我在 jquery 中包含数据标记,则不会命中服务的端点。

标签: json wcf rest no-response


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    }

    【讨论】:

      猜你喜欢
      • 2012-12-13
      • 2010-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多