A robust RESTful API backend for Auction Management System built with ASP.NET Core Web API, featuring JWT authentication, Entity Framework Core, and comprehensive auction and bidding logic.
Features β’ Tech Stack β’ Installation β’ API Documentation β’ Deployment
The Auction Management Backend is a production-ready REST API that powers the complete auction platform. It provides secure endpoints for user authentication, auction management, real-time bidding, and administrative functions with role-based access control.
- π Secure by Design - JWT authentication with role-based authorization
- β‘ High Performance - Optimized database queries with EF Core
- π¦ Well-Structured - Clean architecture with separation of concerns
- π RESTful Design - Standard HTTP methods and status codes
- π Scalable - Designed to handle concurrent bidding operations
- π§ͺ Testable - Dependency injection for easy unit testing
- β User Registration - Secure account creation with validation
- β JWT Authentication - Token-based authentication system
- β Password Hashing - BCrypt password encryption
- β Role-Based Access Control - Admin and User roles
- β Token Refresh - Refresh expired tokens seamlessly
- β Account Verification - Email verification for new users
- β CRUD Operations - Create, read, update, and delete auctions
- β Auction Status - Active, Ended, Cancelled states
- β Time Management - Start and end time validation
- β Search & Filter - Find auctions by category, price, status
- β Image Upload - Support for auction item images
- β Admin Controls - Special privileges for auction management
- β Place Bids - Submit bids on active auctions
- β Bid Validation - Ensure bids meet minimum increment
- β Bid History - Track all bids for each auction
- β Current Winner - Identify highest bidder
- β Auto-Close - Automatically end auctions at deadline
- β Concurrent Handling - Prevent race conditions in bidding
- β Entity Framework Core - Robust ORM for database operations
- β Migrations - Version-controlled database schema
- β Relationships - Properly modeled data associations
- β Validation - Data annotations and fluent validation
- β Soft Delete - Preserve data integrity
- β Logging - Comprehensive application logging
- β Error Handling - Global exception handling middleware
- β API Versioning - Support for multiple API versions
- β CORS - Cross-origin resource sharing configuration
- β Swagger/OpenAPI - Interactive API documentation
- β Health Checks - Monitor application status
- ASP.NET Core Web API
7.0- Modern web framework - C#
11.0- Primary programming language - .NET SDK
7.0- Runtime environment
- Entity Framework Core
7.0- Object-relational mapper - SQL Server - Primary database (configurable)
- SQLite - Development/testing database
- PostgreSQL - Alternative production database
- JWT (JSON Web Tokens) - Token-based authentication
- BCrypt.Net - Password hashing
- ASP.NET Core Identity - User management (optional)
- AutoMapper - Object-to-object mapping
- FluentValidation - Input validation
- Serilog - Structured logging
- Swashbuckle - Swagger/OpenAPI documentation
- Newtonsoft.Json - JSON serialization
- xUnit - Unit testing framework
- Moq - Mocking framework
- FluentAssertions - Assertion library
Before you begin, ensure you have the following installed:
| Requirement | Version | Download |
|---|---|---|
| .NET SDK | 7.0 or higher | Download |
| SQL Server | 2019 or higher | Download |
| Git | Latest | Download |
| Visual Studio / VS Code | Latest | VS / VS Code |
- SQL Server Management Studio (SSMS) - Database management
- Postman - API testing
- Docker - Containerization
git clone https://github.com/Bashi201/Auction-Management-Backend.git
cd Auction-Management-BackendEdit appsettings.json or appsettings.Development.json:
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=AuctionDB;Trusted_Connection=True;TrustServerCertificate=True;"
}
}{
"ConnectionStrings": {
"DefaultConnection": "Host=localhost;Database=AuctionDB;Username=postgres;Password=yourpassword"
}
}{
"ConnectionStrings": {
"DefaultConnection": "Data Source=auction.db"
}
}Add JWT configuration to appsettings.json:
{
"JwtSettings": {
"SecretKey": "YourSuperSecretKeyThatIsAtLeast32CharactersLong!",
"Issuer": "AuctionManagementAPI",
"Audience": "AuctionManagementClient",
"ExpirationMinutes": 60,
"RefreshTokenExpirationDays": 7
}
}
β οΈ Security Warning: Never commit your actual secret key to version control!
dotnet restore# Create initial migration (if not exists)
dotnet ef migrations add InitialCreate
# Update database
dotnet ef database update# Run seeder to add sample data
dotnet run --seed# Development mode
dotnet run
# Or with hot reload
dotnet watch runThe API will be available at:
- HTTPS:
https://localhost:5001 - HTTP:
http://localhost:5000 - Swagger:
https://localhost:5001/swagger
Auction-Management-Backend/
βββ Controllers/ # API endpoints
β βββ AuthController.cs # Authentication endpoints
β βββ AuctionsController.cs # Auction management
β βββ BidsController.cs # Bidding operations
β βββ UsersController.cs # User management
βββ Models/ # Entity models
β βββ User.cs
β βββ Auction.cs
β βββ Bid.cs
β βββ Category.cs
βββ DTOs/ # Data Transfer Objects
β βββ Auth/
β β βββ LoginDto.cs
β β βββ RegisterDto.cs
β β βββ TokenDto.cs
β βββ Auction/
β β βββ CreateAuctionDto.cs
β β βββ UpdateAuctionDto.cs
β β βββ AuctionResponseDto.cs
β βββ Bid/
β βββ PlaceBidDto.cs
β βββ BidResponseDto.cs
βββ Data/ # Database context
β βββ ApplicationDbContext.cs
β βββ DbInitializer.cs
β βββ Migrations/
βββ Services/ # Business logic
β βββ Interfaces/
β β βββ IAuthService.cs
β β βββ IAuctionService.cs
β β βββ IBidService.cs
β βββ Implementations/
β βββ AuthService.cs
β βββ AuctionService.cs
β βββ BidService.cs
βββ Repositories/ # Data access layer
β βββ Interfaces/
β β βββ IUserRepository.cs
β β βββ IAuctionRepository.cs
β β βββ IBidRepository.cs
β βββ Implementations/
β βββ UserRepository.cs
β βββ AuctionRepository.cs
β βββ BidRepository.cs
βββ Middleware/ # Custom middleware
β βββ ErrorHandlingMiddleware.cs
β βββ JwtMiddleware.cs
βββ Helpers/ # Utility classes
β βββ AutoMapperProfile.cs
β βββ JwtHelper.cs
β βββ PasswordHelper.cs
βββ Validators/ # FluentValidation validators
β βββ LoginDtoValidator.cs
β βββ RegisterDtoValidator.cs
β βββ CreateAuctionDtoValidator.cs
βββ appsettings.json # Configuration
βββ appsettings.Development.json # Dev configuration
βββ Program.cs # Application entry point
βββ Startup.cs # Service configuration (if applicable)
βββ AuctionApi.sln # Solution file
βββ .gitignore
βββ Dockerfile # Docker configuration
βββ README.md
https://localhost:5001/api
All protected endpoints require a JWT token in the Authorization header:
Authorization: Bearer <your_jwt_token>
POST /api/auth/registerRequest Body:
{
"firstName": "John",
"lastName": "Doe",
"email": "john.doe@example.com",
"password": "SecurePass123!",
"confirmPassword": "SecurePass123!",
"phoneNumber": "+1234567890"
}Response (201 Created):
{
"success": true,
"message": "Registration successful",
"data": {
"userId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
"email": "john.doe@example.com",
"firstName": "John",
"lastName": "Doe"
}
}cURL Example:
curl -X POST https://localhost:5001/api/auth/register \
-H "Content-Type: application/json" \
-d '{
"firstName": "John",
"lastName": "Doe",
"email": "john.doe@example.com",
"password": "SecurePass123!",
"confirmPassword": "SecurePass123!"
}'POST /api/auth/loginRequest Body:
{
"email": "john.doe@example.com",
"password": "SecurePass123!"
}Response (200 OK):
{
"success": true,
"data": {
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refreshToken": "7d5f8e9a-4b3c-2d1e-0f9g-8h7i6j5k4l3m",
"expiresAt": "2024-12-31T23:59:59Z",
"user": {
"id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
"email": "john.doe@example.com",
"firstName": "John",
"lastName": "Doe",
"role": "User"
}
}
}cURL Example:
curl -X POST https://localhost:5001/api/auth/login \
-H "Content-Type: application/json" \
-d '{
"email": "john.doe@example.com",
"password": "SecurePass123!"
}'POST /api/auth/refreshRequest Body:
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refreshToken": "7d5f8e9a-4b3c-2d1e-0f9g-8h7i6j5k4l3m"
}Response (200 OK):
{
"success": true,
"data": {
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refreshToken": "8e6g9f0b-5c4d-3e2f-1g0h-9i8j7k6l5m4n",
"expiresAt": "2024-12-31T23:59:59Z"
}
}GET /api/auctions?page=1&pageSize=10&status=Active&category=ElectronicsQuery Parameters:
page(int, optional): Page number (default: 1)pageSize(int, optional): Items per page (default: 10)status(string, optional): Filter by status (Active, Ended, Cancelled)category(string, optional): Filter by categorysearchTerm(string, optional): Search in title and descriptionminPrice(decimal, optional): Minimum starting pricemaxPrice(decimal, optional): Maximum starting pricesortBy(string, optional): Sort field (default: createdDate)sortOrder(string, optional): asc or desc (default: desc)
Response (200 OK):
{
"success": true,
"data": {
"items": [
{
"id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"title": "Vintage Camera",
"description": "Rare vintage camera in excellent condition",
"startingPrice": 500.00,
"currentPrice": 750.00,
"imageUrl": "https://example.com/images/camera.jpg",
"startTime": "2024-12-01T10:00:00Z",
"endTime": "2024-12-31T10:00:00Z",
"status": "Active",
"categoryName": "Electronics",
"sellerName": "John Doe",
"totalBids": 15,
"highestBidder": "Jane Smith"
}
],
"currentPage": 1,
"totalPages": 5,
"totalItems": 50,
"pageSize": 10
}
}cURL Example:
curl -X GET "https://localhost:5001/api/auctions?page=1&pageSize=10&status=Active" \
-H "Authorization: Bearer YOUR_JWT_TOKEN"GET /api/auctions/{id}Response (200 OK):
{
"success": true,
"data": {
"id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"title": "Vintage Camera",
"description": "Rare vintage camera in excellent condition. Includes original case and manual.",
"startingPrice": 500.00,
"currentPrice": 750.00,
"imageUrl": "https://example.com/images/camera.jpg",
"startTime": "2024-12-01T10:00:00Z",
"endTime": "2024-12-31T10:00:00Z",
"status": "Active",
"categoryId": "cat-123",
"categoryName": "Electronics",
"sellerId": "user-456",
"sellerName": "John Doe",
"sellerEmail": "john.doe@example.com",
"totalBids": 15,
"highestBid": 750.00,
"highestBidderId": "user-789",
"highestBidderName": "Jane Smith",
"createdAt": "2024-11-01T08:00:00Z",
"updatedAt": "2024-12-15T14:30:00Z"
}
}POST /api/auctionsHeaders:
Authorization: Bearer YOUR_JWT_TOKEN
Content-Type: application/json
Request Body:
{
"title": "Vintage Camera",
"description": "Rare vintage camera in excellent condition",
"startingPrice": 500.00,
"imageUrl": "https://example.com/images/camera.jpg",
"startTime": "2024-12-01T10:00:00Z",
"endTime": "2024-12-31T10:00:00Z",
"categoryId": "cat-123"
}Response (201 Created):
{
"success": true,
"message": "Auction created successfully",
"data": {
"id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"title": "Vintage Camera",
"status": "Pending"
}
}cURL Example:
curl -X POST https://localhost:5001/api/auctions \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"title": "Vintage Camera",
"description": "Rare vintage camera",
"startingPrice": 500.00,
"startTime": "2024-12-01T10:00:00Z",
"endTime": "2024-12-31T10:00:00Z",
"categoryId": "cat-123"
}'PUT /api/auctions/{id}Request Body:
{
"title": "Updated Vintage Camera",
"description": "Updated description",
"startingPrice": 550.00,
"endTime": "2025-01-15T10:00:00Z"
}Response (200 OK):
{
"success": true,
"message": "Auction updated successfully",
"data": {
"id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"title": "Updated Vintage Camera",
"updatedAt": "2024-12-30T15:45:00Z"
}
}DELETE /api/auctions/{id}Response (200 OK):
{
"success": true,
"message": "Auction deleted successfully"
}POST /api/bidsHeaders:
Authorization: Bearer YOUR_JWT_TOKEN
Content-Type: application/json
Request Body:
{
"auctionId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"amount": 800.00
}Response (201 Created):
{
"success": true,
"message": "Bid placed successfully",
"data": {
"bidId": "bid-123",
"auctionId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"amount": 800.00,
"bidTime": "2024-12-30T16:00:00Z",
"isHighestBid": true
}
}cURL Example:
curl -X POST https://localhost:5001/api/bids \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"auctionId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"amount": 800.00
}'GET /api/bids/auction/{auctionId}?page=1&pageSize=20Response (200 OK):
{
"success": true,
"data": {
"items": [
{
"id": "bid-123",
"amount": 800.00,
"bidTime": "2024-12-30T16:00:00Z",
"bidderName": "Jane Smith",
"isWinning": true
},
{
"id": "bid-122",
"amount": 750.00,
"bidTime": "2024-12-30T15:45:00Z",
"bidderName": "Bob Johnson",
"isWinning": false
}
],
"currentPage": 1,
"totalPages": 1,
"totalItems": 15
}
}GET /api/bids/my-bids?page=1&pageSize=10Response (200 OK):
{
"success": true,
"data": {
"items": [
{
"bidId": "bid-123",
"auctionId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"auctionTitle": "Vintage Camera",
"amount": 800.00,
"bidTime": "2024-12-30T16:00:00Z",
"status": "Winning",
"currentHighestBid": 800.00
}
],
"currentPage": 1,
"totalPages": 3,
"totalItems": 25
}
}GET /api/users/profileResponse (200 OK):
{
"success": true,
"data": {
"id": "user-456",
"email": "john.doe@example.com",
"firstName": "John",
"lastName": "Doe",
"phoneNumber": "+1234567890",
"role": "User",
"createdAt": "2024-01-15T10:00:00Z",
"stats": {
"totalBids": 45,
"wonAuctions": 8,
"activeAuctions": 3
}
}
}PUT /api/users/profileRequest Body:
{
"firstName": "John",
"lastName": "Doe",
"phoneNumber": "+1234567890"
}Response (200 OK):
{
"success": true,
"message": "Profile updated successfully",
"data": {
"id": "user-456",
"firstName": "John",
"lastName": "Doe",
"updatedAt": "2024-12-30T17:00:00Z"
}
}PUT /api/users/change-passwordRequest Body:
{
"currentPassword": "OldPass123!",
"newPassword": "NewSecurePass456!",
"confirmNewPassword": "NewSecurePass456!"
}Response (200 OK):
{
"success": true,
"message": "Password changed successfully"
}| Code | Description |
|---|---|
| 200 | OK - Request succeeded |
| 201 | Created - Resource created successfully |
| 204 | No Content - Request succeeded, no content returned |
| 400 | Bad Request - Invalid input |
| 401 | Unauthorized - Authentication required |
| 403 | Forbidden - Insufficient permissions |
| 404 | Not Found - Resource not found |
| 409 | Conflict - Resource conflict (e.g., bid too low) |
| 422 | Unprocessable Entity - Validation errors |
| 500 | Internal Server Error - Server-side error |
- Use strong secret keys (minimum 32 characters)
- Set appropriate token expiration times
- Implement refresh token rotation
- Store tokens securely on the client side
- Minimum 8 characters required
- Must include uppercase, lowercase, number, and special character
- Passwords are hashed using BCrypt with salt
- Implement rate limiting on login attempts
- HTTPS enforced in production
- CORS properly configured
- Input validation on all endpoints
- SQL injection prevention through parameterized queries
- XSS protection enabled
Never commit sensitive data. Use environment variables:
# .env file (not committed)
JWT_SECRET=YourSuperSecretKey
DB_CONNECTION=YourDatabaseConnectionString
SMTP_PASSWORD=YourEmailPassworddotnet testdotnet test /p:CollectCoverage=true /p:CoverageReportFormat=opencover- Import the Postman collection (if provided)
- Set environment variables (base URL, token)
- Run the collection
dotnet publish -c Release -o ./publish# Login to Azure
az login
# Create resource group
az group create --name AuctionAPIRG --location eastus
# Create App Service plan
az appservice plan create --name AuctionAPIPlan --resource-group AuctionAPIRG --sku B1
# Create web app
az webapp create --name auction-api-app --resource-group AuctionAPIRG --plan AuctionAPIPlanaz webapp config connection-string set \
--name auction-api-app \
--resource-group AuctionAPIRG \
--settings DefaultConnection="YOUR_CONNECTION_STRING" \
--connection-string-type SQLAzureaz webapp deployment source config-zip \
--resource-group AuctionAPIRG \
--name auction-api-app \
--src ./publish.zipdocker build -t auction-api:latest .docker run -d -p 8080:80 \
-e ConnectionStrings__DefaultConnection="YOUR_CONNECTION_STRING" \
-e JwtSettings__SecretKey="YOUR_JWT_SECRET" \
--name auction-api \
auction-api:latestdocker tag auction-api:latest yourusername/auction-api:latest
docker push yourusername/auction-api:latest# Install EB CLI
pip install awsebcli
# Initialize EB
eb init -p "64bit Amazon Linux 2 v2.x.x running .NET Core" auction-api
# Create environment and deploy
eb create auction-api-env
eb deploy# Login to Heroku
heroku login
# Create app
heroku create auction-api-app
# Add buildpack
heroku buildpacks:set https://github.com/jincod/dotnetcore-buildpack
# Deploy
git push heroku main
# Set environment variables
heroku config:set JWT_SECRET=YourSecretKey
heroku config:set ConnectionStrings__DefaultConnection="YOUR_CONNECTION"FROM mcr.microsoft.com/dotnet/aspnet:7.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443
FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build
WORKDIR /src
COPY ["AuctionApi.csproj", "./"]
RUN dotnet restore "AuctionApi.csproj"
COPY . .
RUN dotnet build "AuctionApi.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "AuctionApi.csproj" -c Release -o /app/publish
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "AuctionApi.dll"]version: '3.8'
services:
api:
build: .
ports:
- "8080:80"
environment:
- ASPNETCORE_ENVIRONMENT=Production
- ConnectionStrings__DefaultConnection=Server=db;Database=AuctionDB;User=sa;Password=YourPassword123!;
depends_on:
- db
networks:
- auction-network
db:
image: mcr.microsoft.com/mssql/server:2019-latest
environment:
- ACCEPT_EULA=Y
- SA_PASSWORD=YourPassword123!
ports:
- "1433:1433"
volumes:
- sqldata:/var/opt/mssql
networks:
- auction-network
volumes:
sqldata:
networks:
auction-network:
driver: bridgedocker-compose up -d- π§ Email notifications for bid updates
- π Real-time WebSocket notifications
- π³ Payment gateway integration (Stripe/PayPal)
- π± Push notifications
- π Multi-language support
- π Advanced analytics and reporting
- π€ Auto-bidding system
- πΈ Image upload and management
- π Elasticsearch integration for advanced search
- π Rate limiting and throttling
- π Two-factor authentication (2FA)
- π Export data to PDF/Excel
We welcome contributions! Please follow these steps:
- Fork the repository
- Clone your fork
git clone https://github.com/your-username/Auction-Management-Backend.git
- Create a feature branch
git checkout -b feature/amazing-feature
- Make your changes
- Run tests
dotnet test - Commit your changes
git commit -m "Add: Amazing new feature" - Push to your fork
git push origin feature/amazing-feature
- Open a Pull Request
- Follow C# coding conventions
- Write XML documentation for public APIs
- Include unit tests for new features
- Update API documentation
- Keep commits atomic and well-described
# Reset database
dotnet ef database drop
dotnet ef database update- Ensure secret key is at least 32 characters
- Check token expiration time
- Verify Authorization header format:
Bearer {token}
Update Program.cs:
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowAll", builder =>
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});This project is licensed under the MIT License.
MIT License
Copyright (c) 2024 Bashi201
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
Bashi
- π GitHub: @Bashi201
- π§ Email: bashithawanasinghe111@gmail.com
- Microsoft - For ASP.NET Core and Entity Framework
- JWT.io - For JSON Web Token implementation
- Swagger - For API documentation
- Community Contributors - Thank you for your support!
Built with π using ASP.NET Core by Bashi
β If you find this project useful, please give it a star! β