Implementing Web Services in C# with ASMX and ASP.NET Core Examples
ASMX Web Serviecs offer a straightforward approach for creating SOAP-based services in the .NET Framework. A service is defined by a class inheriting from WebService and methods decorated with the [WebMethod] attribute.
// ASMX Service Implementation
using System.Web.Services;
[WebService(Namespace = "http://yournamespace.org/")]
public class CalculationService : WebService
{
[WebMethod]
public decimal SumValues(decimal valueA, decimal valueB)
{
return valueA + valueB;
}
[WebMethod]
public string CreateWelcomeMessage(string userName)
{
return $"Welcome, {userName}!";
}
}
Clients can add a service reference to this endpoint to generate a proxy, allowing remotee invocation of the SumValues and CreateWelcomeMessage methods via SOAP.
For modern development, ASP.NET Core Web APIs provide a RESTful alternative using controller classes. These utilize attribute routing and return structured HTTP rseponses.
// ASP.NET Core Web API Controller
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class ApiCalculatorController : ControllerBase
{
[HttpGet("calculate-sum/{operand1}/{operand2}")]
public ActionResult<decimal> GetSum(int operand1, int operand2)
{
return operand1 + operand2;
}
[HttpGet("welcome-message")]
public ActionResult<string> GetMessage([FromQuery] string visitor)
{
if (string.IsNullOrWhiteSpace(visitor))
return BadRequest("Visitor name must be provided.");
return $"Greetings, {visitor}!";
}
}
In this REST API, the GetSum action is accessible via a GET request to a URL like /api/ApiCalculator/calculate-sum/10/20. The GetMessage action uses a query string parameter, e.g., /api/ApiCalculator/welcome-message?visitor=Alice. The controller methods leverage ActionResult<T> to return HTTP status codes along with the response data.