A feature-rich, production-ready real-time chat application built with .NET 8, SignalR, and modern web technologies.
- Real-time Messaging - Instant message delivery using SignalR WebSockets
- Multi-room Chat - Create and join unlimited chat rooms
- Direct Messaging - Private one-on-one conversations
- User Authentication - Secure JWT-based authentication
- File Sharing - Upload and share images and documents
- Message Reactions - React to messages with emojis
- Typing Indicators - See when others are typing
- Online Presence - Real-time user online/offline status
- Read Receipts - Track message read status
- Message History - Persistent message storage
- User Profiles - Customizable user profiles with avatars
- Message Editing & Deletion - Edit or delete your messages
- Room Management - Create public, private, or password-protected rooms
- Search Functionality - Search messages and users
- Responsive Design - Works perfectly on desktop and mobile
- Real-time Notifications - Get notified of new messages
- Multiple Room Types - Public, Private, and Password-Protected rooms
- Role-based Access - Owner, Admin, Moderator, and Member roles
- Rate Limiting - Built-in API rate limiting
- Health Checks - Application health monitoring
- .NET 8.0 - Latest .NET framework
- ASP.NET Core - Web API framework
- SignalR - Real-time WebSocket communication
- Entity Framework Core 8 - ORM for database operations
- SQL Server - Primary database
- JWT Authentication - Secure token-based auth
- BCrypt - Password hashing
- Serilog - Structured logging
- HTML5/CSS3 - Modern web standards
- Vanilla JavaScript - No framework dependencies
- SignalR Client - Real-time client library
- Font Awesome - Icon library
- Responsive Design - Mobile-first approach
- Repository Pattern - Clean data access layer
- Unit of Work - Transaction management
- Dependency Injection - Loose coupling
- Middleware Pipeline - Error handling, logging
- Clean Architecture - Separation of concerns
- .NET 8 SDK
- SQL Server (LocalDB, Express, or full version)
- Docker (optional, for containerized deployment)
-
Clone the repository
git clone https://github.com/yourusername/dotnet-websocket-chat.git cd dotnet-websocket-chat -
Configure the database connection
Edit
appsettings.json:{ "ConnectionStrings": { "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=ChatAppDb;Trusted_Connection=True;MultipleActiveResultSets=true" } } -
Update JWT settings
Generate a secure secret key (at least 32 characters) in
appsettings.json:{ "JwtSettings": { "SecretKey": "YourSuperSecretKeyThatIsAtLeast32CharactersLong", "Issuer": "ChatApp", "Audience": "ChatAppUsers", "ExpiryInMinutes": 1440 } } -
Create the database
dotnet ef migrations add InitialCreate dotnet ef database update
-
Run the application
dotnet run
-
Open your browser
Navigate to
https://localhost:5001orhttp://localhost:5000
-
Using Docker Compose
docker-compose up -d
-
Access the application
Open
http://localhost:5000
The Docker setup includes:
- ChatApp web application
- SQL Server database
- Automatic database initialization
- Volume mounting for file uploads
ChatApp/
├── Controllers/ # API Controllers
│ ├── AuthController.cs
│ ├── RoomsController.cs
│ ├── MessagesController.cs
│ ├── UsersController.cs
│ └── FilesController.cs
├── Data/ # Data access layer
│ ├── ChatDbContext.cs
│ └── Repositories/
│ ├── IRepository.cs
│ ├── Repository.cs
│ ├── IUnitOfWork.cs
│ └── UnitOfWork.cs
├── Hubs/ # SignalR Hubs
│ └── ChatHub.cs
├── Middleware/ # Custom middleware
│ ├── ErrorHandlingMiddleware.cs
│ └── RequestLoggingMiddleware.cs
├── Models/ # Data models
│ ├── Entities/ # Database entities
│ └── DTOs/ # Data transfer objects
├── Services/ # Business logic
│ ├── AuthService.cs
│ ├── ChatService.cs
│ └── FileService.cs
├── wwwroot/ # Static files
│ ├── css/
│ ├── js/
│ ├── images/
│ └── uploads/
├── appsettings.json # Configuration
├── Program.cs # Application entry point
├── Dockerfile # Docker configuration
└── docker-compose.yml # Docker Compose setup
POST /api/auth/register
Content-Type: application/json
{
"username": "john_doe",
"email": "[email protected]",
"password": "SecurePass123",
"displayName": "John Doe"
}POST /api/auth/login
Content-Type: application/json
{
"usernameOrEmail": "john_doe",
"password": "SecurePass123"
}GET /api/auth/me
Authorization: Bearer {token}POST /api/rooms
Authorization: Bearer {token}
Content-Type: application/json
{
"name": "General Chat",
"description": "A place for general discussion",
"type": "Public",
"maxMembers": 100
}GET /api/rooms/my-rooms
Authorization: Bearer {token}POST /api/rooms/join
Authorization: Bearer {token}
Content-Type: application/json
{
"roomId": "guid",
"password": "optional-for-protected-rooms"
}GET /api/messages/room/{roomId}?skip=0&take=50
Authorization: Bearer {token}GET /api/messages/search?roomId={guid}&query=searchterm
Authorization: Bearer {token}POST /api/files/upload?folder=chat
Authorization: Bearer {token}
Content-Type: multipart/form-data
file: [binary data]SendMessage(messageDto)- Send a chat messageEditMessage(messageId, updateDto)- Edit a messageDeleteMessage(messageId)- Delete a messageAddReaction(reactionDto)- Add emoji reactionRemoveReaction(messageId, emoji)- Remove reactionJoinRoom(roomId)- Join a roomLeaveRoom(roomId)- Leave a roomStartTyping(roomId)- Indicate typingStopTyping(roomId)- Stop typing indicationUpdateStatus(status)- Update online statusSendDirectMessage(messageDto)- Send DM
ReceiveMessage(message)- New message receivedMessageEdited(message)- Message was editedMessageDeleted(data)- Message was deletedReactionAdded(data)- Reaction added to messageReactionRemoved(data)- Reaction removedUserTyping(data)- User is typingUserJoinedRoom(data)- User joined roomUserLeftRoom(data)- User left roomUserStatusChanged(data)- User status changedReceiveDirectMessage(message)- New DM receivedMessageRead(data)- Message was read
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=ChatAppDb;..."
},
"JwtSettings": {
"SecretKey": "your-secret-key-here",
"Issuer": "ChatApp",
"Audience": "ChatAppUsers",
"ExpiryInMinutes": 1440
},
"FileUpload": {
"MaxFileSizeMB": 10,
"AllowedExtensions": [".jpg", ".jpeg", ".png", ".gif", ".pdf", ".doc", ".docx", ".txt"],
"UploadPath": "wwwroot/uploads"
},
"Cors": {
"AllowedOrigins": ["http://localhost:3000", "http://localhost:5173"]
}
}- Id (Guid, PK)
- Username (string, unique)
- Email (string, unique)
- PasswordHash (string)
- DisplayName (string)
- AvatarUrl (string)
- Bio (string)
- Status (enum: Online, Away, Busy, Offline)
- LastSeenAt (DateTime)
- CreatedAt (DateTime)
- Id (Guid, PK)
- Name (string)
- Description (string)
- Type (enum: Public, Private, Protected)
- Password (string, hashed)
- MaxMembers (int)
- CreatedByUserId (Guid, FK)
- CreatedAt (DateTime)
- Id (Guid, PK)
- RoomId (Guid, FK)
- UserId (Guid, FK)
- Content (string)
- Type (enum: Text, Image, File, System)
- AttachmentUrl (string)
- CreatedAt (DateTime)
- UpdatedAt (DateTime)
- IsEdited (bool)
- IsDeleted (bool)
- ReplyToMessageId (Guid, FK)
- Id (Guid, PK)
- RoomId (Guid, FK)
- UserId (Guid, FK)
- Role (enum: Member, Moderator, Admin, Owner)
- JoinedAt (DateTime)
- LastReadAt (DateTime)
- JWT Authentication - Secure token-based authentication
- Password Hashing - BCrypt for password security
- CORS Protection - Configurable allowed origins
- Input Validation - Data annotations and model validation
- SQL Injection Protection - Parameterized queries via EF Core
- XSS Protection - Content sanitization
- Rate Limiting - API endpoint rate limiting
- File Upload Validation - Type and size restrictions
- Database Indexing - Optimized queries with proper indexes
- Async/Await - Non-blocking async operations
- Connection Pooling - Efficient database connections
- Caching - In-memory caching for frequently accessed data
- Compression - Response compression
- SignalR Scaling - Ready for Redis backplane
-
Update configuration
- Change JWT secret key
- Update database connection string
- Configure CORS for production domain
- Set appropriate log levels
-
Database
- Run migrations:
dotnet ef database update - Backup strategy in place
- Connection string secured
- Run migrations:
-
Security
- Enable HTTPS
- Configure secure headers
- Review CORS settings
- Update allowed file types
-
Monitoring
- Set up application insights
- Configure health checks
- Log aggregation
- Performance monitoring
- Azure App Service - Fully managed platform
- Docker/Kubernetes - Containerized deployment
- IIS - Traditional Windows hosting
- Linux Server - Self-hosted with Nginx/Apache
# Watch mode (auto-reload)
dotnet watch run
# With specific environment
dotnet run --environment Development# Add migration
dotnet ef migrations add MigrationName
# Update database
dotnet ef database update
# Remove last migration
dotnet ef migrations remove# Run all tests
dotnet test
# Run with coverage
dotnet test /p:CollectCoverage=true- Fork the repository
- Create a feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
For issues, questions, or contributions:
- Open an issue on GitHub
- Submit a pull request
- Contact: [email protected]
- Voice/Video calling
- Message threading
- Advanced search with filters
- Mobile apps (iOS/Android)
- Desktop apps (Electron)
- Bot integration support
- Custom themes
- Message encryption
- Redis caching
- Elasticsearch integration
- Analytics dashboard
- Admin panel
- ASP.NET Core Team
- SignalR Team
- Entity Framework Core Team
- Open source community
Built with ❤️ using .NET 8 and SignalR