Web service creation & consuming with ASP.NET


Hello all

Today I will show how to create web service with VS2008 and consume it in different application.
first I have opened a web service from File>New web site > web service named "DemoWebService".

now in the solution explorer we can a Service.asmx file and the Service.cs file in App_Code . I have added another web service named WebServiceTest.asmx so a WebServiceTest.cs file also added in App_Code folder.

we will basically work with *.cs file to make the service.
I opened the WebServiceTest.cs file and there is a demo web method named Hello World. So I will create another method named "GetValue" which will also return a string.

using System;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
/// <summary>
///
Summary description for WebServiceTest
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// 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 WebServiceTest : System.Web.Services.WebService {
public WebServiceTest () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string HelloWorld() {
return "Hello World";
}
[WebMethod]
public string GetValue()
{
string valueString = "the result of your logic.";
return valueString;
}
}

We have to add the [WebMethod]  attribute before starting any method which will serve the web service.

Now i will add another web site named "ConsumeWebService" which will be used to consume the web service. and add web reference to the site as bellow.

for the simplicity I have chosen the Web service in this solution( you can choose you own type as you needed for the further use).
now we will see  our Class file which we have created in our web service, I have select the WebServiceTest for the implementing.  

Now we will sell our methods in the next window, now I have selected the web reference name as "WebserviceTest" and add the reference .

for the simplicity I will skip the  discussion of  *.disco & *.wsdl file,this file are basically needed for communication between our application and web service.

now I open the Default.aspx.cs file and add the WebServiceTest namespace and call the Method of web service as following.

no compile the web site and and enjoy the service.

BYE

, , ,

Leave a Reply