2013-08-22 219 views
1

我正在使用asp.net。我已經在C#中創建了一個WCF服務並託管在IIS服務器上。我在我的asp.net web應用程序中使用JQuery調用這個服務。當我使用JQuery調用該服務時,它將會出現錯誤功能,警報中會顯示空的消息。使用JQuery調用WCF服務時WCF服務調用失敗

調用服務表單.aspx頁面。

<script src="Script/jquery-1.10.2.min.js" type="text/javascript"></script> 

<script type="text/javascript" language="javascript"> 
function callService() 
{ 
    var value = 10; 
    $.ajax({ 
     type: "POST", 
     url: "http://localhost/IISWCF/Service1.svc/getdata", 
     contentType: "application/json; charset=utf-8", 
     data: '{"value": "' + value + '"}', 
     dataType: "json", 
     processdata: true, //True or False 
     error: function(XMLHttpRequest, textStatus, errorThrown) { 
      alert("error: " + errorThrown); 
     }, 
     success: function(msg) { 
      alert(msg.d); 
     } 
    }); 
} 
</script> 

<script type="text/javascript" language="javascript"> 
$(document).ready(function(){ 
    callService(); 
}) 
</script> 

Service1.svc文件

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] 
public class Service1 : IService1 
{ 
    public string GetData(int value) 
    { 
     return string.Format("You entered: {0}", value); 
    } 
} 

IService1.cs文件

namespace WcfService1 
{ 
    [ServiceContract] 
    public interface IService1 
    { 

     [OperationContract] 
     [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json)] 
     string GetData(int value); 
    } 
} 

WCF的web.config文件

<system.serviceModel> 
    <behaviors> 
    <serviceBehaviors> 
     <behavior name="WcfService1.Service1Behavior"> 
     <serviceMetadata httpGetEnabled="true"/> 
     <serviceDebug includeExceptionDetailInFaults="false"/> 
     </behavior> 
    </serviceBehaviors> 
    <endpointBehaviors> 
     <behavior name="EndpBehavior"> 
     <webHttp/> 
     </behavior> 
    </endpointBehaviors> 
    </behaviors> 
    <services> 
    <service name="WcfService1.Service1" behaviorConfiguration="WcfService1.Service1Behavior"> 
     <endpoint behaviorConfiguration="EndpBehavior" address="" binding="webHttpBinding" contract="WcfService1.IService1"> 
     <identity> 
      <dns value="localhost"/> 
     </identity> 
     </endpoint> 
     <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> 
    </service> 
    </services> 
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" /> 
</system.serviceModel> 

請幫我解決了這個問題。

+0

嘗試使用此文章中提到的方向,因爲它似乎你可能會需要JSON作爲響應。 WebGet和WebInvoke似乎缺失。 http://www.codeproject.com/Articles/132809/Calling-WCF-Services-using-jQuery –

+0

我已按照鏈接中提到的步驟進行操作,問題未解決。我用新的編輯過我的問題。你可以幫我嗎。 – user2322512

+0

更改端點綁定到webHttpBinding – Erwin

回答

0

我添加了一些虛擬代碼,可能很少有方法也不使用。但是您可以使用虛擬DoubleUp方法測試您的代碼。另外,您已經定義了端點行爲,但是它被使用了,它應該應用於端點及其重要。請參考下面的示例。

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the  interface name "IService1" in both code and config file together. 
[ServiceContract] 
public interface ICalculatorService 
{ 

    [OperationContract] 
    [WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "/DoubleUp/{val}")] 
    int DoubleUp(string val); 

    [OperationContract] 
    [WebGet(ResponseFormat=WebMessageFormat.Json, UriTemplate="/{value}/{value1}")] 
    int AddValues(string value, string value1); 

    [OperationContract] 
    [WebGet(ResponseFormat = WebMessageFormat.Json)] 
    string ConcatenateString(string stringArray); 
} 


public class CalculationService : ICalculatorService 
{ 

    public int DoubleUp(string val) 
    { 
     return 2 * Convert.ToInt32(val); 
    } 

    public int AddValues(string value, string value1) 
    { 
     return Convert.ToInt32(value) + Convert.ToInt32(value1); 
    } 

    public string ConcatenateString(string stringArray) 
    { 
     string returnString = string.Empty; 
     returnString += stringArray;   

     return returnString; 
    } 
} 

<system.serviceModel> 
<bindings> 
    <webHttpBinding> 
    <binding name="JSONBinding"></binding> 
    </webHttpBinding> 
    <basicHttpBinding> 
    <binding name="basicHTTP"> 
     <security mode="None"> 

     </security> 
    </binding> 
    </basicHttpBinding> 
</bindings> 
<behaviors> 
    <serviceBehaviors> 
    <behavior name="basicBehavior"> 
     <!-- To avoid disclosing metadata information, set the values below to false before deployment --> 
     <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/> 
     <!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information --> 
     <serviceDebug includeExceptionDetailInFaults="false"/> 
    </behavior> 
    </serviceBehaviors> 
    <endpointBehaviors> 
    <behavior name="JSON"> 
     <webHttp/> 
    </behavior> 
    </endpointBehaviors> 
</behaviors> 
<services> 
<service name="RestWCFService.CalculationService" behaviorConfiguration="basicBehavior"> 
    <endpoint address="basic" binding="basicHttpBinding" contract="RestWCFService.ICalculatorService" bindingName ="basicHTTP"></endpoint> 
    <endpoint behaviorConfiguration="JSON" binding="webHttpBinding" bindingConfiguration="JSONBinding" contract="RestWCFService.ICalculatorService" name="JSONService"></endpoint> 
    </service>  
</services> 

<protocolMapping> 
    <add binding="basicHttpBinding" scheme="http"/> 
    <add binding="basicHttpsBinding" scheme="https" /> 
</protocolMapping>  
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" /> 
</system.serviceModel> 



/* This is the code for accessing the service via REST call 
     WebClient client = new WebClient(); 
     string s = client.DownloadString("http://localhost/RestWCFService/CalculationService.svc/DoubleUp/3"); 
     Console.WriteLine("Response returned is:" + s); 
     */ 

     /*This is the section to access service via Proxy */ 

     ChannelFactory<RestWCFService.ICalculatorService> client = new ChannelFactory<RestWCFService.ICalculatorService>(); 

     client.Endpoint.Address = new EndpointAddress("http://localhost/RestWCFService/CalculationService.svc/basic"); 
     client.Endpoint.Binding = new BasicHttpBinding(); 
     RestWCFService.ICalculatorService service = client.CreateChannel(); 

     int val = service.DoubleUp("2"); 
     ((IClientChannel)service).Close(); 
     client.Close(); 

     Console.WriteLine("Values returned is:" + val.ToString()); 

     /*Programmatic access ends here */ 

     Console.ReadLine(); 

您的服務工作正常。做了一些改變。

[ServiceContract] 
public interface IService1 
{ 

    [OperationContract] 
    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate="/GetData?value={value}")] 
    string GetData(int value); 
} 

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] 
public class Service1 : IService1 
{ 
    public string GetData(int value) 
    { 
     return string.Format("You entered: {0}", value); 
    } 
} 

<system.serviceModel>  
    <behaviors> 
    <serviceBehaviors> 
     <behavior name="WcfService1.Service1Behavior"> 
     <serviceMetadata httpGetEnabled="true"/> 
     <serviceDebug includeExceptionDetailInFaults="false"/> 
     </behavior> 
    </serviceBehaviors> 
    <endpointBehaviors> 
     <behavior name="EndpBehavior"> 
     <webHttp/> 
     </behavior> 
    </endpointBehaviors> 
    </behaviors> 
    <services> 
    <service name="WcfService1.Service1" behaviorConfiguration="WcfService1.Service1Behavior"> 
     <endpoint behaviorConfiguration="EndpBehavior" address="" binding="webHttpBinding" contract="WcfService1.IService1"> 
     <identity> 
      <dns value="localhost"/> 
     </identity> 
     </endpoint> 
     <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> 
    </service> 
    </services> 
<protocolMapping> 
    <add binding="basicHttpsBinding" scheme="https" /> 
</protocolMapping>  
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" /> 
</system.serviceModel> 

訪問瀏覽器上的服務,你會得到結果。

http://localhost/IISWCF/Service1.svc/GetData?value=1 

如果你的服務工作正常,那麼試試這個JS,因爲你的JS對於這個服務請求是不正確的。

<script type="text/javascript" language="javascript"> 
function callService() { 
    var value = 10; 
    $.ajax({ 
     type: "GET", 
     url: "http://localhost/IISWCF/Service1.svc/GetData?value=1", 
     contentType: "application/json; charset=utf-8", 
     data: '{"value": "' + value + '"}', 
     dataType: "text", 
     processdata: false, //True or False 
     statusCode: { 
      404: function() { 
       alert("page not found"); 
      }, 
      200: function() { 
       alert('HTTP HIT WAS Good.'); 
      }, 
     }, 
     error: function (XMLHttpRequest, textStatus, errorThrown) { 
      alert("error: " + errorThrown); 
     }, 
     success: function (msg) { 
      alert(msg); 
     } 
    }); 
} 

+0

當我使用方法運行服務時,由於EndpointDispatcher中的AddressFilter不匹配,無法在接收方處理帶有To'http:// localhost:61157/Service1.svc/getdata'的消息的錯誤。檢查發件人和收件人的EndpointAddresses是否同意。「但是,如果我將端點webHttpBinding更改爲wsbHttpBinding,則頁面顯示爲空白。你可以幫我嗎。 – user2322512

+0

地址不匹配在URl中出現不匹配的情況可以說您處於域中並獲取http://COMPUTERNAME.DOMAIN/SERVICE,並且您正在指定服務中的本地主機。您可以通過添加[ServiceBehavior(AddressFilterMode = AddressFilterMode.Any)]來刪除它,但對所有請求來說這不是一個好習慣。 –

+0

由於EndpointDispatcher中的ContractFilter不匹配,我添加了[ServiceBehavior(AddressFilterMode = AddressFilterMode.Any)]並且出現錯誤爲「帶有Action的消息」,無法在接收方處理,這可能是由於合同不匹配(發件人和收件人之間的動作不匹配)或發件人和收件人之間的綁定/安全不匹配檢查發件人和收件人是否有相同的合同和相同的綁定(包括安全要求,例如消息,傳輸,無)。任何幫助。 – user2322512