This project implements a lightweight and customizable web server in C#. It provides essential features for handling HTTP requests, routing, and response management, making it a foundational solution for building web applications or APIs.
- Routing System: Dynamically map incoming requests to appropriate handlers.
- Controller Integration: Use attributes to define and manage endpoints effectively.
- Request and Response Management: Handle HTTP requests and generate structured responses.
- Error Handling: Improve error responses for unhandled exceptions or missing routes.
The project consists of the following files:
Server: The entry point for the web server. Handles server startup and listens for incoming requests.Router: Manages routing of requests to their respective handlers.Request: Represents an HTTP request with parsed data like headers, method, and body.RequestHandler: Handles processing of incoming requests and invokes appropriate routes.ResponseHandler: Generates and sends HTTP responses to clients.
RouteAttribute: Enables declarative routing by defining routes directly on methods.ControllerAttribute: Marks a class as a controller to group related endpoints. Controllers decorated with this attribute are automatically scanned and registered by the router.
Controllers: Example or base controllers showcasing route definition and business logic handling.
Program: Contains theMainmethod to bootstrap and start the server.
- .NET 8.0 SDK or later.
- A development environment such as Visual Studio or VS Code.
- Clone the repository:
git clone <repository-url> cd <repository-directory>
- Open the project in your preferred IDE.
- Build the project to restore dependencies and compile the code:
dotnet build
Run the server using the following command:
dotnet runThe server will start and listen on the default port (e.g., http://localhost:5000).
To define new routes:
- Add methods to
Controllers.csor create a new controller file. - Decorate the methods with the
[Route("<path>")]attribute to specify the endpoint.
Example:
[Controller]
public class HelloController {
[Route("/hello")]
public string SayHello() {
return "Hello, world!";
}
}Use tools like Postman or a web browser to send requests to the server and validate responses.
- Middleware: Add support for middleware by enhancing
RequestHandler. - Static File Serving: Implement a handler to serve static files.