We have a ASP.NET website project. In the past, we had been using asmx webservice. Now, we have WCF service, and I am trying to call a WCF service using client proxy object with jQuery. With asmx, it was fairly easy to call a webservice with folllowing lines of code
function GetBooks() {
$.ajax({
type: "POST",
data: "{}",
dataType: "json",
url: "http: /WebService.asmx/GetBooks",
contentType: "application/json; charset=utf-8",
success: onSuccess
});
}
and the method in WebService class is
[WebMethod(EnableSession = true)]
public Books[] GetBooks()
{
List<BooksTO> dtos = BooksDTOUtils.GetBooks(entityOwnerID);
return dtos.ToArray();
}
Now, GetBooks_Wcf() method has to be called from jQuery. I am using a client proxy in new class (WcfCall.cs) to call wcf method GetBooks
public Books[] GetBooksWcf()
{
var service = WcfProxy.GetServiceProxy();
var request = new GetBooksRequest();
request.entityOwnerID= entityOwnerID;
var response = service.GetBooks(request);
returnresponse.Results.ToArray();
}
and my Proxy (Wcfproxy.cs) is
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;
}
So, my question is how do I call GetBooksWcf from jQuery? I have created a reference.cs, and Service.ServiceClient from above method is in reference.cs below. Also, the parameter “entityOwnerID” is sensitive and I cannot pass it from JQuery, either I have to persist it or call from web.config as key.
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public partial class ServiceClient : System.ServiceModel.ClientBase<Service.IService>, Service.IService
{
.........
}
Thanks in advance!
The .NET proxy for your WCF service cannot be used as-is in jQuery.
You need to enable your WCF service to be consumed via JavaScript or jQuery by using
AspNetCompatibilityRequirementsandWebInvokeattributes (see here).