Creating and Consuming Web Service in ASP.NET
Our article regarding, creating and consuming web service in ASP.NET. Step by step article about how to create and call; consume web service in ASP.NET using C#.
In previous articles we explained about Validation Controls, Cross-Page Posting, Create Captcha Image, Binding Dropdownlist and now we will move on Creating and Consuming Web Service in ASP.NET using C#.
- Web Service file (.asmx) contains the Web Service directive, which identifies the public class that implements the Web service logic. The Web service class contains one or more public methods for exposure in a Web service. These Web service methods are prefaced with the Web Method attribute.
- A web service is a web-based functionality accessed using the protocols of the web to be used by the web applications.
- A web service is a web application which is basically a class consisting of methods that could be used by other applications. It also follows code-behind architecture like the ASP.Net web pages, although it does not have a user interface.
Following are the steps to creating and consuming web service in ASP.NET
Create a new website
If you are sound with the ASP.NET then you know very well how to create a website.
LEARN MORE : HOW TO CREATE AN ASP.NET WEBSITE
Add new web service
- Right-click on the Project
- Click on Add -> New Item…
- Select Web Service and change Name as per mention in below figure
- Click on Add button
Code behind file of Web Service
By adding web service you will see following code in code behind file of web service (WebserviceDemo.asmx.cs)
Run Web Service in browser
By running web service in browser you will find list of methods that’s created in web service. In our case you can see the “HelloWorld” method. Click on this method to invoke it.
After clicking on Invoke button you will find following output. This is useful to check whether Web method is working correctly or not?
HTML Markup to access web method
Add button and label controls in Default.aspx. For that add below code in HTML markup and generate button click event to call web service method.
<asp:Button ID="btnPrintHelloWorld" runat="server" Text="Print Hello World" OnClick="btnPrintHelloWorld_Click" />
<asp:Label ID="lblHelloWorld" runat="server" Text="" ForeColor="Red"></asp:Label>
Access web method from web service
Now if you want to access “Helloworld” method on button click event then you have to create an object of web service and call web method.
Code-behind source for button click
protected void btnPrintHelloWorld_Click(object sender, EventArgs e)
WebServiceDemo obj = new WebServiceDemo();
lblHelloWorld.Text = obj.HelloWorld();
RUN PROJECT AND CHECK FINAL OUTPUT
Now just save everything and run project. You will get following figure as output.
Final Output is display as mention in below figure.