Skip to content

codeforgood-org/dotnet-websocket-chat

Repository files navigation

ChatApp - Real-time Communication Platform

A feature-rich, production-ready real-time chat application built with .NET 8, SignalR, and modern web technologies.

.NET 8 SignalR Entity Framework License

Features

Core Functionality

  • 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

Advanced Features

  • 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

Technology Stack

Backend

  • .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

Frontend

  • 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

Architecture

  • 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

Getting Started

Prerequisites

Installation

Option 1: Local Development

  1. Clone the repository

    git clone https://github.com/yourusername/dotnet-websocket-chat.git
    cd dotnet-websocket-chat
  2. Configure the database connection

    Edit appsettings.json:

    {
      "ConnectionStrings": {
        "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=ChatAppDb;Trusted_Connection=True;MultipleActiveResultSets=true"
      }
    }
  3. Update JWT settings

    Generate a secure secret key (at least 32 characters) in appsettings.json:

    {
      "JwtSettings": {
        "SecretKey": "YourSuperSecretKeyThatIsAtLeast32CharactersLong",
        "Issuer": "ChatApp",
        "Audience": "ChatAppUsers",
        "ExpiryInMinutes": 1440
      }
    }
  4. Create the database

    dotnet ef migrations add InitialCreate
    dotnet ef database update
  5. Run the application

    dotnet run
  6. Open your browser

    Navigate to https://localhost:5001 or http://localhost:5000

Option 2: Docker Deployment

  1. Using Docker Compose

    docker-compose up -d
  2. 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

Project Structure

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

API Documentation

Authentication Endpoints

Register

POST /api/auth/register
Content-Type: application/json

{
  "username": "john_doe",
  "email": "[email protected]",
  "password": "SecurePass123",
  "displayName": "John Doe"
}

Login

POST /api/auth/login
Content-Type: application/json

{
  "usernameOrEmail": "john_doe",
  "password": "SecurePass123"
}

Get Current User

GET /api/auth/me
Authorization: Bearer {token}

Room Endpoints

Create Room

POST /api/rooms
Authorization: Bearer {token}
Content-Type: application/json

{
  "name": "General Chat",
  "description": "A place for general discussion",
  "type": "Public",
  "maxMembers": 100
}

Get My Rooms

GET /api/rooms/my-rooms
Authorization: Bearer {token}

Join Room

POST /api/rooms/join
Authorization: Bearer {token}
Content-Type: application/json

{
  "roomId": "guid",
  "password": "optional-for-protected-rooms"
}

Message Endpoints

Get Room Messages

GET /api/messages/room/{roomId}?skip=0&take=50
Authorization: Bearer {token}

Search Messages

GET /api/messages/search?roomId={guid}&query=searchterm
Authorization: Bearer {token}

File Endpoints

Upload File

POST /api/files/upload?folder=chat
Authorization: Bearer {token}
Content-Type: multipart/form-data

file: [binary data]

SignalR Hub Events

Client → Server

  • SendMessage(messageDto) - Send a chat message
  • EditMessage(messageId, updateDto) - Edit a message
  • DeleteMessage(messageId) - Delete a message
  • AddReaction(reactionDto) - Add emoji reaction
  • RemoveReaction(messageId, emoji) - Remove reaction
  • JoinRoom(roomId) - Join a room
  • LeaveRoom(roomId) - Leave a room
  • StartTyping(roomId) - Indicate typing
  • StopTyping(roomId) - Stop typing indication
  • UpdateStatus(status) - Update online status
  • SendDirectMessage(messageDto) - Send DM

Server → Client

  • ReceiveMessage(message) - New message received
  • MessageEdited(message) - Message was edited
  • MessageDeleted(data) - Message was deleted
  • ReactionAdded(data) - Reaction added to message
  • ReactionRemoved(data) - Reaction removed
  • UserTyping(data) - User is typing
  • UserJoinedRoom(data) - User joined room
  • UserLeftRoom(data) - User left room
  • UserStatusChanged(data) - User status changed
  • ReceiveDirectMessage(message) - New DM received
  • MessageRead(data) - Message was read

Configuration

appsettings.json

{
  "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"]
  }
}

Database Schema

Users

  • 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)

Rooms

  • Id (Guid, PK)
  • Name (string)
  • Description (string)
  • Type (enum: Public, Private, Protected)
  • Password (string, hashed)
  • MaxMembers (int)
  • CreatedByUserId (Guid, FK)
  • CreatedAt (DateTime)

Messages

  • 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)

RoomMembers

  • Id (Guid, PK)
  • RoomId (Guid, FK)
  • UserId (Guid, FK)
  • Role (enum: Member, Moderator, Admin, Owner)
  • JoinedAt (DateTime)
  • LastReadAt (DateTime)

Security Features

  • 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

Performance Optimizations

  • 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

Deployment

Production Checklist

  1. Update configuration

    • Change JWT secret key
    • Update database connection string
    • Configure CORS for production domain
    • Set appropriate log levels
  2. Database

    • Run migrations: dotnet ef database update
    • Backup strategy in place
    • Connection string secured
  3. Security

    • Enable HTTPS
    • Configure secure headers
    • Review CORS settings
    • Update allowed file types
  4. Monitoring

    • Set up application insights
    • Configure health checks
    • Log aggregation
    • Performance monitoring

Deployment Options

  • Azure App Service - Fully managed platform
  • Docker/Kubernetes - Containerized deployment
  • IIS - Traditional Windows hosting
  • Linux Server - Self-hosted with Nginx/Apache

Development

Running in Development

# Watch mode (auto-reload)
dotnet watch run

# With specific environment
dotnet run --environment Development

Database Migrations

# Add migration
dotnet ef migrations add MigrationName

# Update database
dotnet ef database update

# Remove last migration
dotnet ef migrations remove

Testing

# Run all tests
dotnet test

# Run with coverage
dotnet test /p:CollectCoverage=true

Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support

For issues, questions, or contributions:

Roadmap

  • 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

Acknowledgments

  • ASP.NET Core Team
  • SignalR Team
  • Entity Framework Core Team
  • Open source community

Built with ❤️ using .NET 8 and SignalR

About

No description, website, or topics provided.

Resources

License

Contributing

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •