Tuesday, 4 February 2014

Write a Simple .asmx Web Service

  1. Open Visual Studio .NET.
  2. On the File menu, click New and then click Project. Under Project types click Visual C# Projects, then click ASP.NET Web Service under Templates. Type MathService in the Location text box to change the default name (WebService1) to MathService.
  3. Change the name of the default Web service that is created from Service1.asmx to MathService.asmx.
  4. Click Click here to switch to code view in the designer environment to switch to code view.
  5. Define methods that encapsulate the functionality of your service. Each method that will be exposed from the service must be flagged with a WebMethod attribute in front of it. Without this attribute, the method will not be exposed from the service.

    NOTE: Not every method needs to have the WebMethod attribute. It is useful to hide some implementation details called by public Web service methods or for the case in which the WebService class is also used in local applications. A local application can use any public class, but only WebMethod methods will be remotely accessible as Web services.

    Add the following method to the MathServices class that you just created:
     
    [WebMethod]
    public int Add(int a, int b)
    {
       return(a + b);
    }
    
    [WebMethod]
    public System.Single Subtract(System.Single A, System.Single B)
    {
       return (A - B);
    }
    
    [WebMethod]
    public System.Single Multiply(System.Single A, System.Single B)
    {
       return A * B;
    }
    
    [WebMethod]
    public System.Single Divide(System.Single A, System.Single B)
    {
       if(B == 0)
          return -1;
       return Convert.ToSingle(A / B);
    }
         
  6. Click Build on the Build menu to build the Web service.
  7. Browse to the MathService.asmx Web service page to test the Web service. If you set the local computer to host the page, the URL is http://localhost/MathService/MathService.asmx.

    The ASP.NET runtime returns a Web Service Help Page that describes the Web service. This page also enables you to test different Web service methods.

No comments:

Post a Comment