Server Project
Controllers > CountryController.cs
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Dapper;
using System.Data;
using System.Data.SQLite;
namespace BlazorCountriesWasm.Server.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class CountryController : ControllerBase
{
private readonly IConfiguration _config;
public CountryController(IConfiguration config)
{
_config = config;
}
public string connectionId = "Default";
public string sqlCommand = "";
IEnumerable<Country>? countries;
[HttpGet]
public async Task<ActionResult<List<Country>>> GetCountries()
{
sqlCommand = "Select * From Country";
using IDbConnection conn = new SQLiteConnection(_config.GetConnectionString(connectionId));
{
countries = await conn.QueryAsync<Country>(sqlCommand);
}
return Ok(countries);
}
[HttpGet]
[Route("{CountryId}")]
//Or you can combine the two lines as: [HttpGet("{CountryId}")]
public async Task<ActionResult<Country>> GetSingleCountry(int CountryId)
{
var country = countries.FirstOrDefault(c => c.CountryId == CountryId);
if (country == null)
{
return NotFound("Sorry, no country found.");
}
else
{
return Ok(country);
}
}
}
}
appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"Default": "Data Source=.\\Data\\countriesandcities.db;Version=3;"
}
}