.NET Web Services
Web services in .NET provide a standardized way for applications to communicate with each other over a network, typically using HTTP. This allows for interoperability between different platforms and programming languages.
The core technologies involved in building and consuming .NET web services include:
Historically, .NET has supported several approaches to web services. The most prominent are:
While ASP.NET Core Web API is preferred for new development, understanding ASMX can be helpful for maintaining existing systems. Here's a simple example:
// MyService.cs
using System.Web.Services;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class MyService : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello, World!";
}
[WebMethod]
public int AddNumbers(int num1, int num2)
{
return num1 + num2;
}
}
To make this service discoverable, you would typically create a file named MyService.asmx in your web application's root directory:
<%@ WebService Language="C#" CodeBehind="MyService.cs" Class="MyService" %>
ASP.NET Core Web API is the modern approach for building HTTP services. It's built on ASP.NET Core, offering cross-platform support, improved performance, and a flexible architecture.
// Controllers/ProductsController.cs
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
private static List _products = new List { "Laptop", "Mouse", "Keyboard" };
[HttpGet]
public ActionResult> Get()
{
return Ok(_products);
}
[HttpGet("{id}")]
public ActionResult Get(int id)
{
if (id < 0 || id >= _products.Count)
{
return NotFound();
}
return Ok(_products[id]);
}
[HttpPost]
public IActionResult Post([FromBody] string product)
{
_products.Add(product);
return CreatedAtAction(nameof(Get), new { id = _products.Count - 1 }, product);
}
}
You can consume web services from various .NET applications:
Tools like HttpClient (for REST APIs) and SoapClient (for ASMX/WCF SOAP services) are commonly used.
This section provides a foundational understanding of .NET web services. For in-depth details on specific technologies like WCF or advanced ASP.NET Core Web API features, please refer to dedicated documentation sections.