Skip to content

3.2 Examples

Play

ASP.NET Basic API

1. Simple Example

A basic example of a simple Web API in ASP.NET Core:

  1. Create a new ASP.NET Core Web API project: Select the project type ASP.NET Core Web App

  2. Startup file structure:

    • The default structure includes a Program.cs, Startup.cs, and a Controllers folder with a sample controller.
  3. 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.

  1. 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.

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:

  1. Create a new Web API project:

    Terminal window
    dotnet new webapi -n SimpleApiServer
  2. 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);
}
}
}
  1. 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();
  1. Run the server:
    Terminal window
    dotnet run
    This starts the server at https://localhost:<port>, and the endpoint https://localhost:<port>/api/weather will return weather data.

2.2 Client: ASP.NET Core Console App

  1. Create a new console project:

    Terminal window
    dotnet new console -n SimpleApiClient
  2. Add a dependency to HttpClient: In SimpleApiClient.csproj, add:

    <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.Http" Version="7.0.0" />
    </ItemGroup>
  3. 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}");
}
}
}
  1. 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.