Introduction
In this article, you will learn what is a web service in ASP.NET, how it communicates with the other web applications and how to create a web service in ASP.NET.
What is a Web Service
A web service is a web application (a piece of software component) which is available on the internet. A web service uses XML format for all the communication with other applications on the internet. It uses XML and JSON data formats and HTTP protocol to communicate with other applications over the internet.
For example, let's say I have created a web application that can convert a string
into uppercase. If I want it to be used by other applications on the internet, then it has to be converted into a web service and should be deployed on the net.
In the next few lines, you will see how to create a web service in ASP.NET and how to use it:
Step 1: Create a web service file and name it "HelloWorld.asmx" in Visual Studio. The extension for a web service file is .asmx:
Step 2: After you have created the web service file, a code file "HelloWorld.vb" will be created in App_Code folder.
Step 3: Open this code file and write your custom code for the web service functionality. This web service will return a "Hello World
" when it is consumed"
1.Imports System.Web
2.Imports System.Web.Services
3.Imports System.Web.Services.Protocols
4.
5.6.7.<WebService(Namespace:="http://tempuri.org/")> _
8.<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
9.<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
10.Public Class HelloWorld
11. Inherits System.Web.Services.WebService
12.
13. <WebMethod()> _
14. Public Function HelloWorld() As String
15. Return "Hello World"
16. End Function
17.
18.End Class
Step 4: Okay. The service is created but how to use it. To use this service, create a simple .aspx page and paste the following code in it. In the action part, put the location of the web service. Here I have used my local host URL. Replace action part with your web service URL.
1.<%@ Page Language="VB" AutoEventWireup="false"
CodeFile="HelloWorld.aspx.vb" Inherits="HelloWorld" %>
2.
3.<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4.
5.<html xmlns="http://www.w3.org/1999/xhtml">
6.<head runat="server">
7. <title></title>
8.</head>
9.<body>
10. <form id="form1" runat="server"
action="http://localhost:49572/wsDemo/HelloWorld.asmx/HelloWorld" method="POST">
11. <input type="submit" value="Run Web Service"> </input>
12. </form>
13.</body>
14.</html>
Step 5: Here is the final output "Hello World
" in the form of XML. You can read this XML data to use in your program.