Мне нужно показать несколько файлов:< /p>
- Program.cs:
Код: Выделить всё
using System.Net;
using Microsoft.EntityFrameworkCore;
using WebApplication1.Data;
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.ConfigureKestrel(options =>
{
options.Listen(IPAddress.Loopback, 7152, listenOptions =>
{
listenOptions.UseHttps();
listenOptions.Protocols = Microsoft.AspNetCore.Server.Kestrel.Core.HttpProtocols.Http1AndHttp2;
});
});
// Add services to the container.
builder.Services.AddControllersWithViews();
// Configure CORS
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowAll", policy =>
{
policy.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
builder.Services.AddDbContext(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("FlightBookingDbContext")));
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCors("AllowAll");
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Homepage}/{id?}");
app.Run();
- appsettings.json:
Код: Выделить всё
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"FlightBookingDbContext": "Server=.;Database=WebProject;Trusted_Connection=True;"
}
}
- AirportService.cs:
Код: Выделить всё
using Microsoft.Data.SqlClient;
public class AirportService
{
private readonly string _connectionString;
public AirportService(string connectionString)
{
_connectionString = connectionString;
}
public List GetAirports()
{
var airports = new List();
using (var connection = new SqlConnection(_connectionString))
{
connection.Open();
var command = new SqlCommand("SELECT * FROM Airport", connection);
var reader = command.ExecuteReader();
while (reader.Read())
{
var airport = new Dictionary
{
{ "Name", reader["name"].ToString() },
{ "Location", reader["location"].ToString() },
{ "IATACode", reader["iata_code"].ToString() },
{ "ICAOCode", reader["icao_code"].ToString() },
{ "Type", reader["type"].ToString() }
};
airports.Add(airport);
}
}
return airports;
}
}
- AirportController.cs:
Код: Выделить всё
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class AirportController : ControllerBase
{
private readonly AirportService _airportService;
public AirportController(IConfiguration configuration)
{
_airportService = new AirportService(configuration.GetConnectionString("DefaultConnection"));
}
[HttpGet]
public IActionResult Get()
{
var airports = _airportService.GetAirports();
return Ok(airports);
}
}
- site.js:
Код: Выделить всё
async function fetchAirports() {
try {
const response = await fetch('https://localhost:7152/api/Airport');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const airports = await response.json();
displayAirports(airports);
} catch (error) {
console.error('Failed to fetch airports:', error);
alert('Có lỗi xảy ra khi lấy danh sách sân bay.');
}
}
function displayAirports(airports) {
const airportTableBody = document.getElementById('airportTable').getElementsByTagName('tbody')[0];
airportTableBody.innerHTML = '';
airports.forEach(airport => {
const row = airportTableBody.insertRow();
row.insertCell(0).textContent = airport.name;
row.insertCell(1).textContent = airport.location;
row.insertCell(2).textContent = airport.iata_code;
row.insertCell(3).textContent = airport.icao_code;
row.insertCell(4).textContent = airport.type;
});
}
document.addEventListener('DOMContentLoaded', function () {
fetchAirports();
});
Подробнее здесь: https://stackoverflow.com/questions/792 ... ty-has-not