We can use a Web Service in an application by the URL of the Web Service so first we need to create a Web Service then create a web application to use the Web Service. For how to create a Web Service read the last article Web Service in ASP.NET: Part -1.
So let's see how to consume a Web Service class [ WebMethod ] in an application.
Step 1
Run Visual Studio then select File -> New WebSite.
Step 2
Now go to Solution Explorer and right-click the Web Site and go to Add Service.
Step 3
Go to Advanced -> Add web Reference.
Now paste the URL of the Web Service into the URL section and provide a Local namespace name for all the Proxy classes from this WebService URL. Finally click on Add Reference.
Step 4
After adding a reference for the Web Service URL it will create all the Proxy classes the same as the [WebService] class from the web URL and It'll also add a new file .discomap to My Solution in a sub folder named local namespace that was defined in the last step.
( .discomap is a DISCO Discovery Output File of a Web Service Application )
And there will be a change in the project file Web.config that is the address of the Web Service of the .asmx file.
Step 5
Now add a web page to call the methods of My Web Service and use the namespace of my Proxy class and create an object of the WebService class.
There are the following 2 methods in the proxy class of every [WebMethod] from a [WebService]:
- SayHello.
- SayHelloAsync
The Async Method calls a method from the Web Service asynchronously.
Calling by normal Method:
Step 6
Now run this Web Page in the browser and you'll get the output after rendering the page. In this case the client page will make a request to the server and the server will create an instance of a Web Service and that type of object is known as a Per Call Object because the request will handle the http:// protocol that is stateless.
We can also call Async methods but they never return a value because when the method process completes then it will call an event and the event calls a method with two parameters (object sender, EventArgs, e) and the e.Result property will return the actual data. First bind the method definition to the completed event and then call your async method.
But on an ASP web form we can't call an async method because it will return an exception at runtime so enable an attribute.
Now run the application again and you will get the same output but by asynchronously.