Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing Web Services in C# with ASMX and ASP.NET Core Examples

Tech May 9 3

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.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.