Three things are to be taken care for a WCF to be invoked from javascript.
- The Service has to be decorated with WebInvoke/WebGet to be accessed from javascript.
<enableWebScript/>
has to be added to the configuration for enabling script calls to WCF.- webHttpBinding is to be used for the WCF to behave as a REST service.
The service have a single method RepeatString:
[OperationContract]
[WebGet(UriTemplate = "/repeatstring",
ResponseFormat= WebMessageFormat.Json)]
string RepeatString(string s, int times);
[OperationContract]
public string RepeatString(string s, int times)
{
string result = "";
for (int i = 0; i < times; ++i)
{
result += s;
}
return result;
}
configuration
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="DatingServiceBehavior">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="DatingServiceBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="DatingServiceBehavior"
name="DatingService.Service.DatingService">
<endpoint address="" binding="webHttpBinding"
contract="DatingService.Service.IDatingService"
behaviorConfiguration="DatingServiceBehavior"/>
<endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />
</service>
</services>
</system.serviceModel>
jqueryfunction callAjaxService1() {
$.post("~/AjaxService1.svc/RepeatString", {s : 'Test', times : 12},
function(data) {
alert('data from service');
}, 'json');
}
No comments:
Post a Comment