ASP.NET WCF Service Application in VB.NET
In this article you will learn how to create a 'WCF Service Application' and Use it in ASP.NET.
Introduction: How to create a 'WCF Service Application' and Use it in other applications of client's.
For Example, Suppose we want to use a WCF service in our 'ASP.NET Web Application' and we don't write any code for that so how it will be possible? For this purpose, read these steps carefully:
Step 1: Open visual studio and click on file menu.
- Go to new -> project.
- New project dialog box will appear.
- Select WCF -> WCF Service Application.
- Give the name as you desire.
- Press ok as shown below on figure:
- Service1.svc.vb will be open.
Step 2: Go to solution explorer.
- open the Iservice1.vb.
- write a code like:
Code:
'NOTE: You can use the "Rename" command on the context menu to change the interface name "IService1" in both code and config file together.
<ServiceContract()>
Public Interface IService1
<OperationContract()>
Function sum(x As Integer, y As Integer) As Integer
<OperationContract()>
Function sendmessage(message As String) As String
' TODO: Add your service operations here
End Interface
Step 3: Now, open the Service1.svc.vb.
Code:
'NOTE: You can use the "Rename" command on the context menu to change the class name "Service1" in code, svc and config file together.
Public Class Service1
Implements IService1
Public Sub New()
End Sub
Public Function sum(x As Integer, y As Integer) As Integer Implements IService1.sum
Return x + y
End Function
Public Function sendmessage(message As String) As String Implements IService1.sendmessage
Console.WriteLine(message)
Return String.Format(" Message Received")
End Function
End Class
Step 4: Start Debugging by pressing F5.
Step 5: Open the visual studio and go to the file menu.
Step 6: Go to Solution Explorer.
-
Right click on 'References' and select 'Add Service Reference...'
-
'Add Service Reference' dialog box will appear.
-
Paste the address which is copied in step 4.
-
Press OK button as shown below in the figure:
Step 7: Now, take a control like 'Button' in the div tag on Form design as shown in the figure:
Code:
Public Class WebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim obj As New ServiceReference1.Service1Client()
Response.Write(obj.sum(5, 4).ToString())
Response.Write(obj.sendmessage("Message received"))
End Sub
End Class
Step 8: Now we press F5 and run this application and result shows like figure below: