Introduction
In this blog post, we’ll walk through creating a sample flight booking application using .NET 8 and C#. Additionally, we’ll integrate a ChatGPT-driven chat functionality to enhance user experience. We will cover the essentials, from setting up the project to implementing the core features and integrating the chat functionality.
Setting Up the Project
First, let’s create a new .NET 8 project. Open your terminal and run:
dotnet new webapi -n FlightBookingApp
cd FlightBookingApp
This will create a new Web API project named FlightBookingApp
.
Configuring the Project
In this section, we’ll set up our project structure and install necessary packages.
Installing Packages
We’ll need a few NuGet packages to help us with our task. Run the following commands to install them:
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package OpenAI
These packages include Entity Framework Core for data access and the OpenAI package to interact with the ChatGPT API.
Creating the Models
We’ll create models for Flight
, Booking
, and User
.
Flight Model
Create a new folder called Models
and add a file named Flight.cs
:
namespace FlightBookingApp.Models
{
public class Flight
{
public int FlightId { get; set; }
public string Airline { get; set; }
public string From { get; set; }
public string To { get; set; }
public DateTime DepartureTime { get; set; }
public DateTime ArrivalTime { get; set; }
public decimal Price { get; set; }
}
}
Booking Model
In the same Models
folder, add a file named Booking.cs
:
namespace FlightBookingApp.Models
{
public class Booking
{
public int BookingId { get; set; }
public int FlightId { get; set; }
public Flight Flight { get; set; }
public int UserId { get; set; }
public User User { get; set; }
public DateTime BookingDate { get; set; }
}
}
User Model
Add another file named User.cs
:
namespace FlightBookingApp.Models
{
public class User
{
public int UserId { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
}
Setting Up the DbContext
We need to set up the DbContext
to manage database operations. Create a folder called Data
and add a file named FlightBookingContext.cs
:
using Microsoft.EntityFrameworkCore;
using FlightBookingApp.Models;
namespace FlightBookingApp.Data
{
public class FlightBookingContext : DbContext
{
public FlightBookingContext(DbContextOptions<FlightBookingContext> options) : base(options)
{
}
public DbSet<Flight> Flights { get; set; }
public DbSet<Booking> Bookings { get; set; }
public DbSet<User> Users { get; set; }
}
}
Configuring the Database
In Program.cs
, configure the database context to use SQL Server:
using FlightBookingApp.Data;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddDbContext<FlightBookingContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Update appsettings.json
with your database connection string:
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=FlightBookingDb;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
Creating Controllers
Next, we’ll create controllers for managing flights and bookings.
FlightController
Create a folder named Controllers
and add a file FlightController.cs
:
using Microsoft.AspNetCore.Mvc;
using FlightBookingApp.Data;
using FlightBookingApp.Models;
using Microsoft.EntityFrameworkCore;
namespace FlightBookingApp.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class FlightController : ControllerBase
{
private readonly FlightBookingContext _context;
public FlightController(FlightBookingContext context)
{
_context = context;
}
[HttpGet]
public async Task<ActionResult<IEnumerable<Flight>>> GetFlights()
{
return await _context.Flights.ToListAsync();
}
[HttpGet("{id}")]
public async Task<ActionResult<Flight>> GetFlight(int id)
{
var flight = await _context.Flights.FindAsync(id);
if (flight == null)
{
return NotFound();
}
return flight;
}
[HttpPost]
public async Task<ActionResult<Flight>> PostFlight(Flight flight)
{
_context.Flights.Add(flight);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetFlight), new { id = flight.FlightId }, flight);
}
}
}
BookingController
Add another file BookingController.cs
:
using Microsoft.AspNetCore.Mvc;
using FlightBookingApp.Data;
using FlightBookingApp.Models;
using Microsoft.EntityFrameworkCore;
namespace FlightBookingApp.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class BookingController : ControllerBase
{
private readonly FlightBookingContext _context;
public BookingController(FlightBookingContext context)
{
_context = context;
}
[HttpGet]
public async Task<ActionResult<IEnumerable<Booking>>> GetBookings()
{
return await _context.Bookings.Include(b => b.Flight).Include(b => b.User).ToListAsync();
}
[HttpPost]
public async Task<ActionResult<Booking>> PostBooking(Booking booking)
{
_context.Bookings.Add(booking);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetBookings), new { id = booking.BookingId }, booking);
}
}
}
Integrating ChatGPT Functionality
To add a chat functionality powered by ChatGPT, we need to set up an endpoint that interacts with the OpenAI API.
ChatController
Add a file ChatController.cs
:
using Microsoft.AspNetCore.Mvc;
using OpenAI;
using OpenAI.Chat;
namespace FlightBookingApp.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ChatController : ControllerBase
{
private readonly OpenAIAPI _openAI;
public ChatController(IConfiguration configuration)
{
_openAI = new OpenAIAPI(configuration["OpenAI:ApiKey"]);
}
[HttpPost]
public async Task<IActionResult> Chat([FromBody] string userMessage)
{
var request = new ChatRequest
{
Messages = new List<Message>
{
new Message { Role = "user", Content = userMessage }
}
};
var response = await _openAI.Chat.CreateChatAsync(request);
var chatResponse = response.Choices.FirstOrDefault()?.Message.Content;
if (chatResponse == null)
{
return BadRequest("Failed to get a response from ChatGPT.");
}
return Ok(new { response = chatResponse });
}
}
}
Summary
In this blog post, we built a flight booking application using .NET 8 and C#. We created models for Flight
, Booking
, and User
, set up a database context, and created controllers to manage flights and bookings. We also integrated a ChatGPT-driven chat functionality to enhance the user experience by allowing users to interact with the system in a conversational manner.
Advantages of Using C# in .NET 8
- Performance: .NET 8 introduces numerous performance improvements, making applications faster and more efficient.
- Cross-Platform: .NET 8 supports building applications that run on various operating systems, including Windows, Linux, and macOS.
- Mature Ecosystem: C# and .NET have a vast library of tools and frameworks, enabling rapid development and reducing time to market.
- Security: .NET provides a robust security framework that helps protect applications against common vulnerabilities.
Benefits of Including ChatGPT Chat Functionality
- Enhanced User Experience: Chat functionality can make the application more interactive and user-friendly.
- Automated Support: Users can get instant responses to their queries, improving customer satisfaction and reducing the need for human support.
- Personalization: ChatGPT can help tailor responses based on user input, providing a more personalized experience.
- 24/7 Availability: Chatbots can provide round-the-clock assistance, ensuring users can get help whenever they need it.
By leveraging the power of .NET 8 and integrating advanced AI functionalities, you can create robust and user-friendly applications that stand out in today’s competitive market.