Cách xây dựng một API trong ASP.NET Core MVC để lấy dữ liệu từ CSDL, với chức năng tìm tên tỉnh hoặc xã dựa vào tham số truyền vào
/api/location
code
: Mã tỉnh/xã (2 ký tự viết hoa).type
: "province"
hoặc "commune"
để xác định cần lấy tên tỉnh hay xã.Tạo một model để biểu diễn dữ liệu tỉnh và xã.
public class Location
{
public string Code { get; set; } // Mã tỉnh/xã
public string Name { get; set; } // Tên tỉnh/xã
}
Định nghĩa DbContext để làm việc với CSDL (SQL Server).
using Microsoft.EntityFrameworkCore;
public class LocationDbContext : DbContext
{
public DbSet<Location> Provinces { get; set; }
public DbSet<Location> Communes { get; set; }
public LocationDbContext(DbContextOptions<LocationDbContext> options) : base(options) { }
}
Tạo một API Controller để xử lý request.
using Microsoft.AspNetCore.Mvc;
using System.Linq;
[Route("api/location")]
[ApiController]
public class LocationController : ControllerBase
{
private readonly LocationDbContext _context;
public LocationController(LocationDbContext context)
{
_context = context;
}
[HttpGet]
public IActionResult GetLocation([FromQuery] string code, [FromQuery] string type)
{
if (string.IsNullOrEmpty(code) || string.IsNullOrEmpty(type))
return BadRequest("Thiếu tham số 'code' hoặc 'type'.");
if (type.ToLower() == "province")
{
var province = _context.Provinces.FirstOrDefault(p => p.Code == code);
if (province != null)
return Ok(new { Name = province.Name });
}
else if (type.ToLower() == "commune")
{
var commune = _context.Communes.FirstOrDefault(c => c.Code == code);
if (commune != null)
return Ok(new { Name = commune.Name });
}
return NotFound("Không tìm thấy dữ liệu.");
}
[HttpGet("list")]
public IActionResult GetLocationList([FromQuery] string type, [FromQuery] string provinceCode)
{
if (string.IsNullOrEmpty(type))
return BadRequest("Thiếu tham số 'type'.");
if (type.ToLower() == "province")
{
var provinces = _context.Provinces.Select(p => new { Code = p.Code, Name = p.Name }).ToList();
return Ok(provinces);
}
else if (type.ToLower() == "commune")
{
if (string.IsNullOrEmpty(provinceCode))
return BadRequest("Thiếu tham số 'provinceCode' để lấy danh sách xã.");
var communes = _context.Communes
.Where(c => c.ProvinceCode == provinceCode)
.Select(c => new { Code = c.Code, Name = c.Name })
.ToList();
return Ok(communes);
}
return BadRequest("Tham số 'type' phải là 'province' hoặc 'commune'.");
}
}
appsettings.json
Thêm chuỗi kết nối đến CSDL.
{
"ConnectionStrings": {
"DefaultConnection": "Server=YOUR_SERVER;Database=YOUR_DB;User Id=YOUR_USER;Password=YOUR_PASSWORD;"
}
}
Program.cs
Đăng ký LocationDbContext.
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddDbContext<LocationDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
var app = builder.Build();
app.UseRouting();
app.UseAuthorization();
app.MapControllers();
app.Run();
Gửi yêu cầu GET đến API:
GET /api/location?code=HN&type=province # Trả về "Hà Nội"
GET /api/location?code=BD&type=commune # Trả về "Ba Đình"
GET /api/location/list?type=province # Trả về danh sách tất cả tỉnh
GET /api/location/list?type=commune&provinceCode=HN # Trả về danh sách các xã của Hà Nội