3.2 Examples
ASP.NET Basic API
1. Simple Example
A basic example of a simple Web API in ASP.NET Core:
-
Create a new ASP.NET Core Web API project: Select the project type
ASP.NET Core Web App
-
Startup file structure:
- The default structure includes a
Program.cs
,Startup.cs
, and aControllers
folder with a sample controller.
- The default structure includes a
-
Controller:
- A controller in ASP.NET Core is where the API logic goes. For example:
using Microsoft.AspNetCore.Mvc;
namespace SimpleApi.Controllers{ [Route("api/[controller]")] [ApiController] public class WeatherController : ControllerBase { // GET: api/weather [HttpGet] public IActionResult GetWeather() { var weather = new { Temperature = "22°C", Condition = "Sunny" }; return Ok(weather); } }}
Explanation:
-
[Route(“api/[controller]”)]:
Defines the route of the controller.[controller]
is a placeholder that will use the controller’s class name (Weather
). -
[ApiController]:
Declares this class as an API controller which will handle HTTP requests. -
HttpGet():
Indicates this method will respond to HTTP GET requests. The client can call this method to retrieve weather data. -
IActionResult:
Represents the result of an action method.Ok()
returns a status 200 OK response with the weather data.
- Running the API:
- Use
dotnet run
from the project folder to start the API. - Navigate to
https://localhost:<port>/api/weather
to get the weather data.
- Use
This is the simplest form of a Web API in ASP.NET Core.
2. Client and Server
Here’s a basic setup for an ASP.NET Core Web API server and a client to interact with it.
2.1 Server: ASP.NET Core Web API
Steps to create a simple Web API server:
-
Create a new Web API project:
Terminal window dotnet new webapi -n SimpleApiServer -
Controller (e.g., WeatherController):
In Controllers/WeatherController.cs
, add:
using Microsoft.AspNetCore.Mvc;
namespace SimpleApiServer.Controllers{ [Route("api/[controller]")] [ApiController] public class WeatherController : ControllerBase { // GET: api/weather [HttpGet] public IActionResult GetWeather() { var weather = new { Temperature = "22°C", Condition = "Sunny" }; return Ok(weather); } }}
- Program.cs (no changes needed, but for context):
var builder = WebApplication.CreateBuilder(args);var app = builder.Build();
app.MapControllers(); // Maps the controller route
app.Run();
- Run the server:
This starts the server at
Terminal window dotnet runhttps://localhost:<port>
, and the endpointhttps://localhost:<port>/api/weather
will return weather data.
2.2 Client: ASP.NET Core Console App
-
Create a new console project:
Terminal window dotnet new console -n SimpleApiClient -
Add a dependency to
HttpClient
: InSimpleApiClient.csproj
, add:<ItemGroup><PackageReference Include="Microsoft.Extensions.Http" Version="7.0.0" /></ItemGroup> -
HttpClient setup to call the API:
In Program.cs
, write the client code:
using System;using System.Net.Http;using System.Threading.Tasks;
class Program{ static async Task Main(string[] args) { var client = new HttpClient(); string apiUrl = "https://localhost:<port>/api/weather"; // Replace with actual port
try { var response = await client.GetAsync(apiUrl); response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync(); Console.WriteLine($"Weather data: {content}"); } catch (HttpRequestException e) { Console.WriteLine($"Request error: {e.Message}"); } }}
- Run the client:
Terminal window dotnet run
Explanation
- Server: The Web API controller exposes the
/api/weather
endpoint which returns a weather object in JSON format. - Client: A console app uses
HttpClient
to send a GET request to the Web API and prints the response.
This demonstrates a simple client-server communication using ASP.NET Core Web API and a console app.