How to do it: Developing an ASP.NET Web Service

Description Article
Table of Contents
Summary

Visual Studio solution-ASP.NET Web Service

Note

Implementing a basic ASP.NET web service requires no configuration  on the file “Web.Config” file

Operations
File Common.Data.cs

This file contains the definition of the complex class types sent on the service request and expected as service response

How to do it
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Serialization;
using System.Xml;
using System.Xml.Serialization;

namespace ASPNET
{
    [Serializable]
    [XmlRoot(Namespace="www.training.com", IsNullable=false,ElementName="Category")]
    public class Category
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public string Description { get; set; }
    }
}
File TestService.asmx.cs

Web-service definition with hosting configuration

How to do it
<%@ WebService Language="C#" CodeBehind="TestService.asmx.cs" Class="ASPNET.TestService" %>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Xml;
using System.Xml.Serialization;

namespace ASPNET
{
    /// <summary>
    /// Summary description for TestService
    /// </summary>
    [WebService(Namespace = "http://www.training.com/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 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 TestService : System.Web.Services.WebService
    {

        #region "Operations/Services"
        [WebMethod]
        public Category getCategory(Int32 pId)
        {
            //TODO: Put code here to retrieve category...
            return loadCategory(pId);
        }

        [WebMethod]
        public int addCategory(Category pCategory)
        {
            //TODO: Put code here to save category defintion and return new identifier
            return 10;
        }

        [WebMethod]
        [return: XmlRoot(ElementName = "Categories")]
        public List<Category> getCategories()
        {
            //TODO: Put code here to retrieve category objects...
            return loadCategories();
        }
#endregion

        #region "Private methods"
        private Category loadCategory(int pId)
        {
            return new Category { Id = 1, Name = string.Format("category #{0}", pId), Description = string.Format("test category #{0}", pId) };
        }

        private List<Category> loadCategories()
        {
            return new List<Category>() {
                            new Category { Id=1, Name="category #1", Description= "test category #1"},
                            new Category { Id=2, Name="category #2", Description= "test category #2"} };
        }
        #endregion
    }
}