Creating and Using a Web Service in ASP.NET Web Forms

By Mar 02, 2017

Description:

Creating and Using a Web Service in ASP DOT NET Web Forms

Preferencesoft

In this article, we will see how to create a Web Service in ASP.NET Web Forms. We will look at all ways to call a Web Service method and how to retrieve the result.

Introduction

A Web Service is an application on a Web server that can be called by other programs across the Web. The application is located at an internet address (http://www.site.com/WebService1 for example), and you invoke it by launching a HTTP request. You can provide parameters and in return you will receive data.

 In ASP.NET, a Web Service is actually declared as a class derived from System.Web.Services.WebService. To make a method accessible from the Web service, simply attach the attribute WebMethod and make public access.

Creating a Web Service

Create a .asmx file in root folder.
For this, go to Project, Add a new element, select Visual C#  > Web > Web Service (ASMX), name the file WebService1.asmx

Here is the file created WebService1.asmx:

namespace WebApplicationAsp
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {
 
        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
    }
}

Calling a Web Service

There are several ways to call a method of a Web Service.

The easiest way is to call a method from the code behind, on the server side.

In the Default.aspx page, create a button and a Label.

In Default.aspx, add:

      <br />
        <asp:Button ID="Button1" runat="server" Text="Call 1" OnClick="Button1_Click" />
        <asp:Label ID="Label1" runat="server" Text="Response 1"></asp:Label>
       <br />

Double click the button to access the Default.aspx.cs page.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
namespace WebApplicationAsp
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
 
        }
 
        protected void Button1_Click(object sender, EventArgs e)
        {
            WebService1 testWebService = new WebService1();
            string hello = testWebService.HelloWorld();
            Label1.Text = WebUtility.HtmlEncode(hello);
        }
    }
}

In WebService1.asmx, replace return "Hello World"; by return "<Hello World>";

Call 1

After clicking:

Response 1

When the web service is not on the current site, call it with an HTTP request.

In Default.aspx, add:

       <asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Call 2" />
        <asp:Label ID="Label2" runat="server" Text="Response 2"></asp:Label>
        <br />

       protected void Button2_Click(object sender, EventArgs e)
        {
            WebRequest request = WebRequest.Create("http://localhost:54735/WebService1.asmx/HelloWorld ");
            // Set the POST Method.  
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = 0;
            WebResponse response = request.GetResponse();
            Stream dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.  
            string responseFromServer = reader.ReadToEnd();
            // The string is embedded in a XML string
            string s = string.Empty;
            using (XmlReader xr = XmlReader.Create(new StringReader(responseFromServer)))
            {
                xr.ReadStartElement();
                s = xr.Value;
            }
            // Clean up the streams.  
            reader.Close();
            dataStream.Close();
            response.Close();
            Label2.Text = WebUtility.HtmlEncode(s);
        }

 

Call 2

After clicking:

Response 2

Now let's see how to call a Web service from JavaScript code.

To call a Web service in JavaScript, we will use the function ajax of the jQuery library. In addition, we will choose to transfer the data in Json format.

Create another Web Service WebService2.asmx:

using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Web.Services;
 
namespace WebApplicationAsp
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    [System.Web.Script.Services.ScriptService]
    public class WebService2 : System.Web.Services.WebService
    {
 
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string Hello()
        {
            return "{\"name\":\"Hello\"}";
        }
    }
}

And add this code in Default.aspx:

        <button id="btnHello" type="button" onclick="hello();">Hello</button>
 
        <script type="text/javascript" src="Scripts/jquery-3.1.1.min.js"></script>
        <script type="text/javascript">
                function hello() {
                    $.ajax({
                        type: "POST",
                        //url: '<%= ResolveUrl("~/WebService2.asmx/hello") %>',
                        url: '/WebService2.asmx/hello',
                        data: "{ }",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (msg) {
                            var data = JSON.parse(msg.d);
                            alert(data.name);
                        },
                        error: function (xhr, status, message) {
                            alert("Status: " + status + "\nMessage: " + message);
                        }
                    });
                    return false; // Cancel the default action of the click.
                }
        </script>

ASP.NET

Categories

Share

Follow


KodFor Privacy Policy