articles

Home / DeveloperSection / Articles / Web Services in ASP.Net

Web Services in ASP.Net

Anonymous User9262 31-Jul-2010

Web services are used to give websites program functionality via internet. Web services can accept messes and can return replies.

Example

A simple example to demonstrate, how to design and use that web services in our website.

Web service has “.asmx” extension.

To designing web service select New Project and in the New Project dialog box select “ASP.NET Web Service Application”

Web Services in ASP.Net

Now once the ASP.NET Web Service Application page opened we will do some coding part. 

Code (WebService1.asmx.cs)

 

//before writing any method in web service we have to write “[WebMethod]”
//within square brakets”[ ]”.
 
[WebMethod]
//creating method Add which will accept two arguments.
        publicint Add(int a, int b)
        {
//returning value
            return a + b;
        }

 

Now, we need to compile the application and add the compiled application to IIS


in  order to get its web refrence, as we have to add its web refrence where we have


to use it.

 

Example to demonstrate how to use Web service in our website
Designing website

Web Services in ASP.Net

Web Site design code(Default.aspx)

 

<formid="form1"runat="server">
    <asp:TextBoxID="TextBox2"runat="server"
        style="z-index: 1; left: 397px; top: 112px; position: absolute; width: 194px"></asp:TextBox>
    <asp:TextBoxID="TextBox1"runat="server"
       
        style="z-index: 1; left: 396px; top: 78px; position: absolute; width: 194px"></asp:TextBox>
    <asp:ButtonID="btnAdd"runat="server"onclick="btnAdd_Click"
        style="z-index: 1; left: 414px; top: 141px; position: absolute; height: 26px"
        Text="Add"/>
    <asp:LabelID="Label2"runat="server"Text="TextBox2"
        style="position: absolute; top: 114px; left: 329px;"></asp:Label>
    <asp:LabelID="Label1"runat="server"Text="TextBox1"
        style="position: absolute; top: 79px; left: 329px;"></asp:Label>
    </form>
Code for adding two numbers in text boxes using the web service

Before writing the code we need to add the web reference of the web service. To add web reference of the web service right click in “Solution Explorer” and select “Add Web Reference”,   add web reference dialog box will appear. There add the web reference of the service in my case it is http://localhost:51481/Service1.asmx.

Web Services in ASP.Net

Code for website
 
//code for add button click
protectedvoid btnAdd_Click(object sender, EventArgs e)
      {
//creating object of service created earlier.
        localhost.Service1 ws = new localhost.Service1();
//using Add method of web service and displaying the result in the page.
  Response.Write((ws.Add(int.Parse(TextBox1.Text), int.Parse(TextBox2.Text))).ToString());
      }
Screen shot of web page

Web Services in ASP.Net



Updated 04-Mar-2020
I am a content writter !

Leave Comment

Comments

Liked By