One of the greatest features of WCF 3.5 is direct accessibility of WCF Service on ASP.Net page. Before that there is no direct way to call WCF 3.0 Service on ASP.Net page and you have to create a communication bridge in the form of Web service. Here you find on my blogs how to call AJAX-Enable WCF service from ASP.Net page.
Here is my interface called IoperationService and its implementation class OperationService.
namespace AJAXEnableServices
{
[ServiceContract(Namespace = "AJAXServices")]
public interface IOperationService
{
[OperationContract]
long Add(long x,int y);
}
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class OperationService : IOperationService
{
public long Add(long x,int y)
{
return x + y;
}
}
}
|
Save the preceding code in "AJAXEnableService.cs" file.
The AspNetCompatibilityRequirements attribute apply on the WCF service to make it ASP.Net Compatible code. At runtime, application can detect if ASP.Net compatibility mode is enabled by checking the value of the static property AspNetCompatibilityEnabled. By default AspNetCompatibilityRequirements RequirementsMode is set on NotAllowed.
Create a file with .svc extension and add the following line of code that allow the WCF Service to call on HTTP.
<%@ServiceHost language=c# Debug="true" Service="AJAXEnableServices.OperationService" %>
|
Save it OperationService.svc.
Now it a time to call our WCF service from client side, so we need to an Default.aspx page.
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>WCF Service Test Page.</title>
<script language="javascript" type="text/javascript">
function callService()
{
var n1 = document.getElementById("num1").value;
var n2 = document.getElementById("num2").value;
var service = new AJAXEnableServices.OperationService();
service.Add(parseFloat(n1), parseFloat(n2), onSuccess, null, null);
}
function onSuccess(result)
{
document.getElementById("result").value = result;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>
AJAX-Enable WCF Service Client Page</h1>
<p>
First Number:
<input type="text" id="num1" /></p>
<p>
Second Number:
<input type="text" id="num2" /></p>
</div>
<div>Result:
<input type="text" id="result" /></p>
</div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
<services>
<asp:servicereference Path="OperationService.svc" />
</services>
</asp:ScriptManager>
</form>
<p>
<input id="Button1" type="button" value="Price for 3 Sandwiches" onclick="return callService()" />
</p>
</body>
</html>
|
In the end call the Default.aspx page.