2012-06-14 101 views
1

我們有一個ASP.NET網站項目。在過去,我們一直在使用asmx webservice。現在,我們有WCF服務,並且我正嘗試使用jQuery使用客戶端代理對象來調用WCF服務。隨着ASMX,這是很容易調用web服務與代碼使用客戶端代理對象從jQuery調用WCF服務

function GetBooks() { 
    $.ajax({ 
     type: "POST", 
     data: "{}", 
     dataType: "json", 
     url: "http: /WebService.asmx/GetBooks", 
     contentType: "application/json; charset=utf-8", 
     success: onSuccess 
    }); 
} 

folllowing線和WebService類的方法是

[WebMethod(EnableSession = true)] 
public Books[] GetBooks() 
{ 
     List<BooksTO> dtos = BooksDTOUtils.GetBooks(entityOwnerID); 
     return dtos.ToArray(); 
} 

現在,GetBooks_Wcf()方法必須從jQuery的調用。我正在使用新的類(WcfCall.cs)的客戶端代理來調用WCF方法GetBooks

public Books[] GetBooksWcf() 
{ 
     var service = WcfProxy.GetServiceProxy(); 
     var request = new GetBooksRequest(); 
     request.entityOwnerID= entityOwnerID; 
     var response = service.GetBooks(request); 
     returnresponse.Results.ToArray(); 
} 

和我的代理(Wcfproxy.cs)是

public static Service.ServiceClient GetServiceProxy() 
{ 
    var Service = Session["Service"] as Service.ServiceClient; 
    if (Service == null) 
    { 
     // create the proxy 
     Service = CreateServiceInstance(); 

     // store it in Session for next usage 
     Session["Service"] = Service; 
    } 

    return Service; 
} 

    public static Service.ServiceClient CreateServiceInstance() 
    { 
    ServicePointManager.ServerCertificateValidationCallback = new  RemoteCertificateValidationCallback(IgnoreCertificateErrorHandler); 

    string configValue = Environment.GetConfigSettingStr("WcfService"); 

    Service.ServiceClient webService = new Service.ServiceClient(); 
    //Here is my WCF endpoint 
    webService.Endpoint.Address = new System.ServiceModel.EndpointAddress(configValue); 

    return webService; 
} 

所以,我的問題是,我該怎麼辦從jQuery調用GetBooksWcf?我創建了一個reference.cs,而上面的Service.ServiceClient方法在reference.cs下面。此外,參數「entityOwnerID」是敏感的,我不能從JQuery傳遞它,要麼我必須堅持它或從web.config調用爲關鍵。

[System.Diagnostics.DebuggerStepThroughAttribute()] 
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] 
    public partial class ServiceClient : System.ServiceModel.ClientBase<Service.IService>, Service.IService 
    { 
     ......... 
    } 

在此先感謝!

回答

1

您的WCF服務的.NET代理無法在jQuery中按原樣使用。

您需要通過使用AspNetCompatibilityRequirementsWebInvoke屬性(請參閱here),使您的WCF服務能夠通過JavaScript或jQuery使用。

+0

感謝您的回答和鏈接。但是,在鏈接中,WCF服務被稱爲'function WCFJSON(){var userid =「1」; .. Url =「Service.svc/GetUser」; Data ='{「Id」:「'+ userid +'」}'; .. .. 。}'你會看到userid是如何硬編碼的。我無法從jQuery傳遞參數(因爲userid是敏感信息,我必須調用一個類方法來獲取它)。此時,我最終將asmx用作url:「http:/WebService.asmx/GetBooks」,「 ,並從那裏調用我的代理類,有什麼更好的想法嗎? – ACS

+0

jQuery調用通過線路傳輸,與應用程序中任何其他客戶端元素具有相同的安全性,如果您打算保持用戶標識「安全」,則可以如果你將用戶ID存儲在Session或等效的服務器端存儲中,或者只是依賴傳輸安全性(如HTTPS),那麼仍然可以使用WCF。 – Channs