In this tutorial, I'll show you how to create a web service in c# and call it with webform and winform applications.
1. Create web service:
+) Open MS Visual Studio: File > New > Web Site
Choose ASP.NET Web Service |
This's default service after created.
[WebMethod] public string HelloWorld() { return "Hello World"; }+) Add new service under (for example add a sum function):
[WebMethod] public int Sum(int a, int b) { return a + b; }+) And now click Start Debugging, you can see a webpage like this.
Done Step 1!
2: Call web service from .aspx website.
+) Keep web service running
+) Create new ASP.Net Web Site
Choose ASP.NET Web Site |
2 TextBox, 1 Button, 1 Label |
- Url: Paste your web service link from Step 1 > Press GO
- Web reference name: [Your reference name] > Press Add Reference
protected void Button1_Click(object sender, EventArgs e) { // Get object and convert to int32 int a = Convert.ToInt32(TextBox1.Text); int b = Convert.ToInt32(TextBox2.Text); // Define web service demowebservice.Service mySv = new demowebservice.Service(); // Calculation int result = mySv.Sum(a, b); // Show result Label1.Text = "Result: " + result.ToString(); }+) Click run the website and done!
Note: Keep web service running when testing.
3. Call web service from winform:
+) Create new window form with same design like:
+) Add Service reference: On menu Project > Add Service Reference
- Address: Link to web service > Click GO
- Namespace: Name of service reference
private void button1_Click(object sender, EventArgs e) { // Get object and convert to Int32 int a = Convert.ToInt32(textBox1.Text); int b = Convert.ToInt32(textBox2.Text); // Define web service ServiceReference1.ServiceSoapClient service = new ServiceReference1.ServiceSoapClient(); // Calculation int result = service.Sum(a, b); // Show result label1.Text = "Result: " + result.ToString(); }+) Run app and enjoy: