2011-12-21 42 views
2

我在最近幾天一直在尋找這個問題,並且無處可去。我嘗試了各種教程,出於各種原因,我無法獲得任何工作。我想要做的就是使用jQuery從簡單的HTML頁面調用WCF服務。我現在所得到的只是「不好的要求」。使用jQuery使用WCF服務

我有一切託管在IIS中的同一個虛擬目錄,所以它絕對不是一個跨域問題。

這裏是我的web.config

<?xml version="1.0"?> 
<configuration> 
    <system.web> 
    <compilation debug="true" targetFramework="4.0"/> 
    </system.web> 
    <system.serviceModel> 
    <behaviors> 
     <serviceBehaviors> 
     <behavior name="ServiceBehavior"> 
      <serviceMetadata httpGetEnabled="true"/> 
      <serviceDebug includeExceptionDetailInFaults="true"/> 
     </behavior> 
     </serviceBehaviors> 
     <endpointBehaviors> 
    <behavior name="ServiceBehavior"> 
     <webHttp/> 
    </behavior> 
    </endpointBehaviors> 
</behaviors> 
<services> 
    <service behaviorConfiguration="ServiceBehavior" name="WcfJqueryTest"> 
    <endpoint address="" binding="webHttpBinding" contract="WcfJqueryTest.IService" behaviorConfiguration="ServiceBehavior"/> 
    </service> 
</services> 
</system.serviceModel> 
    <system.webServer> 
<modules runAllManagedModulesForAllRequests="true"/> 
    </system.webServer> 
</configuration> 

這裏是我的服務代碼和接口

namespace WcfJqueryTest 
{ 
[ServiceContract] 
public interface IService 
{ 

    [OperationContract] 
    [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)] 
    string GetData(); 
} 

namespace WcfJqueryTest 
{ 
public class Service : IService 
{ 
    public string GetData() 
    { 
     return "Hello world"; 
    } 
} 
} 

最後我的jQuery

function myFunction() { 
$.ajax({ 
    type: "POST", 
    url: "http://localhost/wcfjquerytest/service.svc/getdata", 
    contentType: "application/json; charset=utf-8", 
    processData: true, 
    dataType: "json", 
    success: function (data) { 
     alert(data); 
    }, 
    error: function (xhr, status, error) { 
     alert(status); 
     alert(error); 
    } 
}) 
}; 

我已經嘗試了許多的教程和搜索到處都是,但我依然不明智。任何指針都非常感謝。

乾杯,

尼爾。

+0

看看:http://www.west-wind.com/weblog/posts/2008/Apr/21/jQuery-AJAX-calls-to-a-WCF-REST-Service – 2011-12-21 15:55:46

+0

我見過他之前的教程,並嘗試使用它,但無濟於事。 – 2011-12-21 17:09:26

+0

嘗試在服務中啓用跟蹤,它應該說明爲什麼它將請求視爲不好。 – carlosfigueira 2011-12-21 17:40:12

回答

0

你可以試試這個,右鍵單擊您的SVC文件,然後單擊「查看標記」

<%@ ServiceHost 
    Language="C#" 
    Debug="true" 
    Service="MyService.Service" 
    CodeBehind="Service.svc.cs" 
    Factory="System.ServiceModel.Activation.WebServiceHostFactory" //Add this line 
%> 

這將自動配置服務(它會取代你在web.config中進行的設置)。

+0

謝謝。我已經嘗試過,現在我得到**內部服務器錯誤**。我認爲有一些追蹤的時間。 – 2011-12-22 08:53:34

+0

看起來像我的IIS有幾個問題,一臺機器重新啓動,它現在工作,乾杯:-) – 2011-12-22 14:23:32