Access an AJAX Enabled WCF Service using ASP.NET and Client Script
Posted by: Suprotim Agarwal ,
on 11/26/2008,
in
Category ASP.NET
Abstract: In this article, we will see how to create an AJAX-enabled WCF Service and how to consume it using client-side script in an ASP.NET page. I have kept the example quiet simple so in order to keep our focus on creating and consuming AJAX Enabled WCF Services.
Access an AJAX Enabled WCF Service using ASP.NET and Client Script
In this article, we will see how to create an AJAX-enabled WCF Service and how to consume it using client-side script in an ASP.NET page. I have kept the example quiet simple so in order to keep our focus on creating and consuming AJAX Enabled WCF Services.
What is AJAX Enabled WCF Service by the way?
In simple words, AJAX-enabled WCF Service is a service that can be consumed using an AJAX client-side script.
The easiest method to create an AJAX-enabled WCF Service is to use the ‘AJAX-enabled WCF Service’ Template in Visual Studio. Let us see how.
Step 1: Create an ASP.NET 3.5 website
Step 2: Right click the project > Add New Item > Choose ‘AJAX-enabled WCF Service’ from the Templates > name the service as ‘GreetingService’ > Add.
Step 3: If you observe the GreetingService.cs/GreetingService.vb gets added in the App_Code directory. The GreetingService.svc serves as the EndPoint. Also observe the web.config that now contains the <system.serviceModel> to describe your new endpoint. This endpoint enables us to create a client-side AJAX proxy class, which in turn can be used to call our service.
Open the GreetingService.cs or vb to implement operations to be exposed in the service. Specify the Namespace for ServiceContractAttribute as ‘GreetNM’:
[ServiceContract(Namespace = "GreetNM")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class GreetingService
{
Note: For users who are familiar with client side web service calls in an ASP.NET AJAX Extensions-enabled page, will observe that the class namespace is used in the WCF service and not in the client proxy.
Add a new method called GreetUser(string uname) which takes a username and returns a string with the “Hello” greeting appended to the user name. Decorate the method with the ‘OperationContractAttribute’ to indicate that the method is a part of the contract.
C#
// Add more operations here and mark them with [OperationContract]
[OperationContract]
public string GreetUser(string uname)
{
return "Hello " + uname;
}
VB.NET
' Add more operations here and mark them with <OperationContract()>
<OperationContract()> _
Public Function GreetUser(ByVal uname As String) As String
Return "Hello " & uname
End Function
Step 4: Now open Default.aspx. Go the Design mode and drag and drop a <ScriptManager> from the AJAX Extensions tab in the toolbox. With the ScriptManager selected, open the ‘Services’ collection in the Properties window
The ‘ServiceReference Collection Editor’ window opens up. Click Add and in the Path specify ‘GreetingService.svc’ > OK.
If you go back to the Source view, the action adds a ServiceReference to the <Services> element
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/GreetingService.svc" />
</Services>
</asp:ScriptManager>
You can also directly add the reference instead of using the ServiceReference Collection Editor. What we have essentially done is that we have registered the AJAX-enabled WCF service with the ScriptManager by adding a ServiceReference and specifying the address to the GreetingService.svc. The ScriptManager in turn will generate the script to create the client proxy through an HTTP handler.
Step 5: Now add a HTML Button, an HTML Input box and a <div> to the Default.aspx page. After renaming the controls and adding the onClick event of the button, the markup will appear similar to the following:
<input id="btnCallWCF" type="button" value="Greet User" onclick="return btnCallWCF_onclick()" />
<input id="txtUNm" type="text" />
<div id="dispGreeting">
The JavaScript code for the click event is as shown below:
<script language="javascript" type="text/javascript">
function btnCallWCF_onclick() {
}
</script>
</head>
Step 6: Call the service. You will notice how the intellisense brings up the GreetNM namespace. If you remember, we added a namespace to the service called ‘GreetNM’.
[ServiceContract(Namespace = "GreetNM")]
Hence when the client-side script proxy is created, it is now in the GreetNM namespace.
Add code to call the WCF Service using client side script as shown below
<head runat="server">
<title>Create AJAX-enabled WCF Service</title>
<script language="javascript" type="text/javascript">
function btnCallWCF_onclick() {
var greeto = new GreetNM.GreetingService();
greeto.GreetUser($get("txtUNm").value, OnGreetingComplete, OnError);
}
function OnGreetingComplete(result) {
$get("dispGreeting").innerHTML = result;
}
function OnError(result) {
alert(result.get_message());
}
</script>
</head>
The results are shown below.
How does the AJAX-enabled WCF service work internally?
I would recommend you reading this post. The internal working along with the JSON serialization/deserialization has been explained very well in this blog.
<%@ ServiceHost Language="C#" Debug="true" Service="GreetingService" CodeBehind="~/App_Code/GreetingService.cs" Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory" %>
This Factory, automatically adds an ASP.NET AJAX endpoint to a service, without you needing to add the configuration details in the web.config file.
That’s it for now. In future posts, we will see some practical examples of using AJAX-enabled WCF service. Until then, stay tuned! I hope you liked the article and I thank you for viewing it. The entire source code of this article can be downloaded from here.
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!
Was this article worth reading? Share it with fellow developers too. Thanks!
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of
DotNetCurry,
DNC Magazine for Developers,
SQLServerCurry and
DevCurry. He has also authored a couple of books
51 Recipes using jQuery with ASP.NET Controls and
The Absolutely Awesome jQuery CookBook.
Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.
Get in touch with him on Twitter @suprotimagarwal or at LinkedIn