{"id":26478048,"url":"https://github.com/neckerfree/dotnet-highperf-apis","last_synced_at":"2026-05-18T08:31:15.403Z","repository":{"id":280074620,"uuid":"940911362","full_name":"NeckerFree/dotnet-highperf-apis","owner":"NeckerFree","description":"Best practices for designing high-performance RESTful APIs on . NET Core","archived":false,"fork":false,"pushed_at":"2025-04-02T05:59:36.000Z","size":691,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"dev","last_synced_at":"2025-04-02T06:33:04.875Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/NeckerFree.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2025-03-01T03:25:59.000Z","updated_at":"2025-04-02T05:59:33.000Z","dependencies_parsed_at":null,"dependency_job_id":"bdc4743f-c9cf-4c4b-aeec-32178315b051","html_url":"https://github.com/NeckerFree/dotnet-highperf-apis","commit_stats":null,"previous_names":["neckerfree/dotnet-highperf-apis"],"tags_count":0,"template":false,"template_full_name":"microverseinc/readme-template","purl":"pkg:github/NeckerFree/dotnet-highperf-apis","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/NeckerFree%2Fdotnet-highperf-apis","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/NeckerFree%2Fdotnet-highperf-apis/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/NeckerFree%2Fdotnet-highperf-apis/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/NeckerFree%2Fdotnet-highperf-apis/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/NeckerFree","download_url":"https://codeload.github.com/NeckerFree/dotnet-highperf-apis/tar.gz/refs/heads/dev","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/NeckerFree%2Fdotnet-highperf-apis/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":33170818,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-18T05:43:36.989Z","status":"ssl_error","status_checked_at":"2026-05-18T05:43:19.133Z","response_time":71,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-03-20T00:59:00.238Z","updated_at":"2026-05-18T08:31:15.372Z","avatar_url":"https://github.com/NeckerFree.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003ca name=\"readme-top\"\u003e\u003c/a\u003e\n\n\u003c!--\n!!! IMPORTANT !!!\nThis README is an example of how you could professionally present your codebase. \nWriting documentation is a crucial part of your work as a professional software developer and cannot be ignored. \n\nYou should modify this file to match your project and remove sections that don't apply.\n\nREQUIRED SECTIONS:\n- Table of Contents\n- About the Project\n  - Built With\n  - Live Demo\n- Getting Started\n- Authors\n- Future Features\n- Contributing\n- Show your support\n- Acknowledgements\n- License\n\nOPTIONAL SECTIONS:\n- FAQ\n\nAfter you're finished please remove all the comments and instructions!\n\nFor more information on the importance of a professional README for your repositories: https://github.com/microverseinc/curriculum-transversal-skills/blob/main/documentation/articles/readme_best_practices.md\n--\u003e\n\n\u003cdiv align=\"center\"\u003e\n  \u003c!-- You are encouraged to replace this logo with your own! Otherwise you can also remove it. --\u003e\n  \u003cimg src=\"murple_logo.png\" alt=\"logo\" width=\"140\"  height=\"auto\" /\u003e\n  \u003cbr/\u003e\n\n  \u003ch3\u003e\u003cb\u003eMicroverse README Template\u003c/b\u003e\u003c/h3\u003e\n\n\u003c/div\u003e\n\n\u003c!-- TABLE OF CONTENTS --\u003e\n\n# 📗 Table of Contents\n\n- [📖 About the Project](#about-project)\n  - [🛠 Built With](#built-with)\n    - [Tech Stack](#tech-stack)\n    - [Key Features](#key-features)\n  - [🚀 Live Demo](#live-demo)\n- [💻 Getting Started](#getting-started)\n  - [Prerequisites](#prerequisites)\n  - [Setup](#setup)\n  - [Install](#install)\n  - [Usage](#usage)\n  - [Run tests](#run-tests)\n  - [Deployment](#deployment)\n- [👥 Authors](#authors)\n- [🔭 Future Features](#future-features)\n- [🤝 Contributing](#contributing)\n- [⭐️ Show your support](#support)\n- [🙏 Acknowledgements](#acknowledgements)\n- [❓ FAQ (OPTIONAL)](#faq)\n- [📝 License](#license)\n\n\u003c!-- PROJECT DESCRIPTION --\u003e\n\n# 📖 [dotnet-highperf-apis] \u003ca name=\"about-project\"\u003e\u003c/a\u003e\n\n**[dotnet-highperf-apis]** is a project that demonstrates best practices about how to build high-performance APIs using .NET Core.\nE-Commerce Application with .NET and AI Tools\nThis project demonstrates how to create a high-performance e-commerce application from scratch using .NET and leverage AI tools like GitHub Copilot and IntelliCode to accelerate development. The application includes a frontend (Razor Pages or MVC) and a backend (RESTful APIs) with a focus on scalability, performance, and maintainability.\n## 🛠 Built With \u003ca name=\"built-with\"\u003e\u003c/a\u003e\n\n### Tech Stack \u003ca name=\"tech-stack\"\u003e\u003c/a\u003e\n\n\u003e Describe the tech stack and include only the relevant sections that apply to your project.\n\n\u003cdetails\u003e\n  \u003csummary\u003eClient\u003c/summary\u003e\n  \u003cul\u003e\n    \u003cli\u003e\u003ca href=\"https://reactjs.org/\"\u003eReact.js\u003c/a\u003e\u003c/li\u003e\n  \u003c/ul\u003e\n\u003c/details\u003e\n\n\u003cdetails\u003e\n  \u003csummary\u003eServer\u003c/summary\u003e\n  \u003cul\u003e\n    \u003cli\u003e\u003ca href=\"https://expressjs.com/\"\u003eExpress.js\u003c/a\u003e\u003c/li\u003e\n  \u003c/ul\u003e\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003eDatabase\u003c/summary\u003e\n  \u003cul\u003e\n    \u003cli\u003e\u003ca href=\"https://www.postgresql.org/\"\u003ePostgreSQL\u003c/a\u003e\u003c/li\u003e\n  \u003c/ul\u003e\n\u003c/details\u003e\n\n\u003c!-- Features --\u003e\n\n### Key Features \u003ca name=\"key-features\"\u003e\u003c/a\u003e\n\nDesigning high-performance RESTful APIs in .NET Core requires careful consideration of various factors, including architecture, coding practices, and infrastructure. Below are some **best practices** to help you build efficient, scalable, and maintainable APIs:\n\nFrontend: React TS for a responsive user interface.\n\nBackend: RESTful APIs built with ASP.NET Core for high performance and scalability.\n\nAI Tools: Leverage GitHub Copilot and IntelliCode for code generation, unit testing, and debugging.\n\nHigh-Performance Practices: Asynchronous programming, caching, database optimization, and more.\n\n### 1. **Use AI Tools to create the app from scratch\nCreating an e-commerce application from scratch using .NET and leveraging integrated AI tools in Visual Studio (like GitHub Copilot and IntelliCode) can significantly accelerate development. Below is a step-by-step guide to help you take full advantage of these tools:\n\n---\n\n#### **Step 1: Set Up Your Development Environment**\n1. **Install Visual Studio**:\n   - Download and install the latest version of Visual Studio with the .NET workload.\n   - Ensure you have the necessary components for web development (e.g., ASP.NET Core).\n\n2. **Enable AI Tools**:\n   - Install and enable **GitHub Copilot** and **IntelliCode** from the Visual Studio Marketplace.\n   - Configure Copilot with your GitHub account and IntelliCode with your preferences.\n\n3. **Create a New Project**:\n   - Open Visual Studio and create a new ASP.NET Core Web Application.\n   - Choose the **Model-View-Controller (MVC)** or **Razor Pages** template, depending on your preference.\n\n---\n\n#### **Step 2: Design the Application Architecture**\n1. **Define the Core Components**:\n   - **Models**: Product, Order, Cart, User, etc.\n   - **Controllers**: ProductController, OrderController, CartController, etc.\n   - **Views**: Product list, product details, cart view, checkout page, etc.\n   - **Services**: ProductService, OrderService, PaymentService, etc.\n\n2. **Use AI Tools to Generate Boilerplate Code**:\n   - Use Copilot to generate initial classes for models, controllers, and services.\n   - For example, type:\n     ```csharp\n     // Generate a Product model with properties like Id, Name, Price, and Description\n     ```\n     Copilot will suggest a complete class definition.\n\n---\n\n#### **Step 3: Implement the Product Catalog**\n1. **Create the Product Model**:\n   - Use Copilot to generate the `Product` class:\n     ```csharp\n     public class Product\n     {\n         public int Id { get; set; }\n         public string Name { get; set; }\n         public decimal Price { get; set; }\n         public string Description { get; set; }\n         public string ImageUrl { get; set; }\n     }\n     ```\n\n2. **Scaffold the Product Controller**:\n   - Use Visual Studio's scaffolding tools to generate a controller for the `Product` model.\n   - Enhance the generated code with Copilot by asking it to add methods for filtering, sorting, and pagination.\n\n3. **Create Views for Product Listing**:\n   - Use Copilot to generate Razor views for displaying products.\n   - For example, type:\n     ```html\n     \u003c!-- Generate a Razor view to display a list of products --\u003e\n     ```\n     Copilot will suggest a complete view with a table or grid layout.\n\n---\n\n#### **Step 4: Implement the Shopping Cart**\n1. **Create the Cart Model**:\n   - Use Copilot to generate the `Cart` and `CartItem` classes:\n     ```csharp\n     public class Cart\n     {\n         public List\u003cCartItem\u003e Items { get; set; } = new List\u003cCartItem\u003e();\n         public decimal TotalPrice =\u003e Items.Sum(item =\u003e item.Price * item.Quantity);\n     }\n\n     public class CartItem\n     {\n         public int ProductId { get; set; }\n         public string ProductName { get; set; }\n         public decimal Price { get; set; }\n         public int Quantity { get; set; }\n     }\n     ```\n\n2. **Add Cart Functionality**:\n   - Use Copilot to generate methods for adding, removing, and updating items in the cart.\n   - For example, type:\n     ```csharp\n     // Generate a method to add a product to the cart\n     ```\n     Copilot will suggest the implementation.\n\n3. **Create Cart Views**:\n   - Use Copilot to generate Razor views for displaying the cart and handling user interactions.\n\n---\n\n#### **Step 5: Implement User Authentication**\n1. **Scaffold Identity**:\n   - Use Visual Studio's built-in Identity scaffolding to add user authentication.\n   - Enhance the generated code with Copilot to customize the login, registration, and profile management pages.\n\n2. **Secure Controllers and Actions**:\n   - Use Copilot to add authorization attributes to controllers and actions:\n     ```csharp\n     [Authorize(Roles = \"Admin\")]\n     public class AdminController : Controller\n     {\n         // Admin-only actions\n     }\n     ```\n\n---\n\n#### **Step 6: Implement Order Processing**\n1. **Create the Order Model**:\n   - Use Copilot to generate the `Order` and `OrderItem` classes:\n     ```csharp\n     public class Order\n     {\n         public int Id { get; set; }\n         public string UserId { get; set; }\n         public DateTime OrderDate { get; set; }\n         public decimal TotalPrice { get; set; }\n         public List\u003cOrderItem\u003e Items { get; set; } = new List\u003cOrderItem\u003e();\n     }\n\n     public class OrderItem\n     {\n         public int ProductId { get; set; }\n         public string ProductName { get; set; }\n         public decimal Price { get; set; }\n         public int Quantity { get; set; }\n     }\n     ```\n\n2. **Implement Checkout Functionality**:\n   - Use Copilot to generate the checkout process, including payment integration (e.g., Stripe or PayPal).\n\n---\n\n#### **Step 7: Use IntelliCode for Code Quality**\n1. **Leverage IntelliCode Suggestions**:\n   - As you write code, IntelliCode will provide context-aware suggestions for methods, properties, and parameters.\n   - Use its recommendations to improve code quality and adhere to best practices.\n\n2. **Refactor Code**:\n   - Use IntelliCode's refactoring tools to simplify and optimize your code.\n\n---\n\n#### **Step 8: Automate Testing with AI**\n1. **Generate Unit Tests**:\n   - Use Copilot to generate unit tests for your controllers, services, and models.\n   - For example, type:\n     ```csharp\n     // Generate unit tests for the ProductService class\n     ```\n     Copilot will suggest test cases.\n\n2. **Run and Validate Tests**:\n   - Use Visual Studio's Test Explorer to run the generated tests and ensure they pass.\n\n---\n\n#### **Step 9: Deploy the Application**\n1. **Set Up CI/CD**:\n   - Use GitHub Actions or Azure DevOps to automate the build and deployment process.\n   - Use Copilot to generate the pipeline configuration file.\n\n2. **Deploy to Azure**:\n   - Use Visual Studio's built-in tools to deploy the application to Azure App Service.\n\n---\n\n#### **Step 10: Document and Share**\n1. **Document the Process**:\n   - Use Copilot to generate documentation for your application, including setup instructions and usage guidelines.\n\n2. **Share Your Work**:\n   - Push your code to GitHub and share it with the community.\n   - Write a blog post or create a video tutorial to showcase how you leveraged AI tools to build the application.\n\n---\n\n#### **Example: Using Copilot to Generate a Product Service**\n```csharp\n// Prompt: Generate a ProductService class with methods to get all products, get a product by ID, and add a new product\npublic class ProductService\n{\n    private readonly List\u003cProduct\u003e _products = new();\n\n    public IEnumerable\u003cProduct\u003e GetAllProducts() =\u003e _products;\n\n    public Product GetProductById(int id) =\u003e _products.FirstOrDefault(p =\u003e p.Id == id);\n\n    public void AddProduct(Product product)\n    {\n        product.Id = _products.Count + 1;\n        _products.Add(product);\n    }\n}\n```\n\n---\n\n### 2. **Use Asynchronous Programming**\n   - **Why**: Asynchronous programming allows your API to handle more requests by freeing up threads while waiting for I/O-bound operations (e.g., database queries, file I/O, or external API calls).\n   - **How**: Use `async` and `await` for all I/O-bound operations.\n   - **Example**:\n     ```csharp\n     public async Task\u003cIActionResult\u003e GetItemAsync(int id)\n     {\n         var item = await _repository.GetItemByIdAsync(id);\n         if (item == null)\n         {\n             return NotFound();\n         }\n         return Ok(item);\n     }\n     ```\n\n---\n\n### 3. **Optimize Database Access**\n   - **Use Efficient Queries**: Write optimized SQL queries or use an ORM like Entity Framework Core efficiently (e.g., avoid `SELECT *`).\n   - **Use Indexing**: Ensure proper indexing on frequently queried columns.\n   - **Pagination**: Implement pagination for large datasets to reduce response size and improve performance.\n     ```csharp\n     public async Task\u003cIActionResult\u003e GetItemsAsync(int page = 1, int pageSize = 10)\n     {\n         var items = await _repository.GetItemsAsync(page, pageSize);\n         return Ok(items);\n     }\n     ```\n\n---\n\n### 4. **Use Caching**\n   - **Why**: Caching reduces the load on your server and database by serving frequently requested data from memory.\n   - **How**:\n     - Use in-memory caching (`IMemoryCache`) for small, frequently accessed data.\n     - Use distributed caching (e.g., Redis) for scalable applications.\n   - **Example**:\n     ```csharp\n     public async Task\u003cIActionResult\u003e GetItemAsync(int id)\n     {\n         if (_memoryCache.TryGetValue($\"Item_{id}\", out var item))\n         {\n             return Ok(item);\n         }\n\n         item = await _repository.GetItemByIdAsync(id);\n         if (item == null)\n         {\n             return NotFound();\n         }\n\n         _memoryCache.Set($\"Item_{id}\", item, TimeSpan.FromMinutes(5));\n         return Ok(item);\n     }\n     ```\n\n---\n\n### 5. **Minimize Payload Size**\n   - **Why**: Smaller payloads reduce network latency and improve response times.\n   - **How**:\n     - Use compression (e.g., Gzip or Brotli) for responses.\n     - Return only the necessary fields (e.g., use DTOs or projection).\n   - **Example**:\n     ```csharp\n     public async Task\u003cIActionResult\u003e GetItemSummaryAsync(int id)\n     {\n         var item = await _repository.GetItemSummaryByIdAsync(id);\n         if (item == null)\n         {\n             return NotFound();\n         }\n         return Ok(item);\n     }\n     ```\n\n---\n\n### 6. **Use Proper HTTP Methods and Status Codes**\n   - **Why**: Proper use of HTTP methods and status codes improves API usability and clarity.\n   - **How**:\n     - Use `GET` for retrieving data, `POST` for creating resources, `PUT`/`PATCH` for updates, and `DELETE` for deletions.\n     - Return appropriate HTTP status codes (e.g., `200 OK`, `201 Created`, `400 Bad Request`, `404 Not Found`, `500 Internal Server Error`).\n\n---\n\n### 7. **Implement Rate Limiting**\n   - **Why**: Rate limiting prevents abuse and ensures fair usage of your API.\n   - **How**: Use middleware like `AspNetCoreRateLimit` to enforce rate limits.\n   - **Example**:\n     ```csharp\n     services.AddMemoryCache();\n     services.Configure\u003cIpRateLimitOptions\u003e(Configuration.GetSection(\"IpRateLimiting\"));\n     services.AddSingleton\u003cIIpPolicyStore, MemoryCacheIpPolicyStore\u003e();\n     services.AddSingleton\u003cIRateLimitCounterStore, MemoryCacheRateLimitCounterStore\u003e();\n     services.AddSingleton\u003cIRateLimitConfiguration, RateLimitConfiguration\u003e();\n     ```\n\n---\n\n### 8. **Enable Compression**\n   - **Why**: Compressing responses reduces bandwidth usage and improves performance.\n   - **How**: Use middleware to enable response compression.\n   - **Example**:\n     ```csharp\n     services.AddResponseCompression(options =\u003e\n     {\n         options.EnableForHttps = true;\n     });\n\n     app.UseResponseCompression();\n     ```\n\n---\n\n### 9. **Use Dependency Injection**\n   - **Why**: Dependency Injection (DI) promotes loose coupling and makes your code more testable and maintainable.\n   - **How**: Register services in the DI container and inject them into controllers or other services.\n   - **Example**:\n     ```csharp\n     services.AddScoped\u003cIItemRepository, ItemRepository\u003e();\n     ```\n\n---\n\n### 10. **Monitor and Log**\n   - **Why**: Monitoring and logging help you identify performance bottlenecks and errors.\n   - **How**:\n     - Use logging frameworks like Serilog or NLog.\n     - Use Application Performance Monitoring (APM) tools like Application Insights or Prometheus.\n   - **Example**:\n     ```csharp\n     public async Task\u003cIActionResult\u003e GetItemAsync(int id)\n     {\n         _logger.LogInformation(\"Fetching item with ID {Id}\", id);\n         var item = await _repository.GetItemByIdAsync(id);\n         if (item == null)\n         {\n             _logger.LogWarning(\"Item with ID {Id} not found\", id);\n             return NotFound();\n         }\n         return Ok(item);\n     }\n     ```\n\n---\n\n### 11. **Use API Versioning**\n   - **Why**: Versioning ensures backward compatibility and allows you to evolve your API without breaking existing clients.\n   - **How**: Use libraries like `Microsoft.AspNetCore.Mvc.Versioning`.\n   - **Example**:\n     ```csharp\n     services.AddApiVersioning(options =\u003e\n     {\n         options.DefaultApiVersion = new ApiVersion(1, 0);\n         options.AssumeDefaultVersionWhenUnspecified = true;\n         options.ReportApiVersions = true;\n     });\n     ```\n\n---\n\n### 12. **Secure Your API**\n   - **Why**: Security is critical to protect sensitive data and prevent unauthorized access.\n   - **How**:\n     - Use HTTPS to encrypt data in transit.\n     - Implement authentication (e.g., JWT, OAuth2) and authorization.\n     - Validate and sanitize all inputs to prevent injection attacks.\n   - **Example**:\n     ```csharp\n     services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)\n             .AddJwtBearer(options =\u003e\n             {\n                 options.TokenValidationParameters = new TokenValidationParameters\n                 {\n                     ValidateIssuer = true,\n                     ValidateAudience = true,\n                     ValidateLifetime = true,\n                     ValidateIssuerSigningKey = true,\n                     ValidIssuer = Configuration[\"Jwt:Issuer\"],\n                     ValidAudience = Configuration[\"Jwt:Audience\"],\n                     IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration[\"Jwt:Key\"]))\n                 };\n             });\n     ```\n\n---\n\n### 13. **Load Testing and Profiling**\n   - **Why**: Load testing helps identify performance bottlenecks under heavy traffic.\n   - **How**:\n     - Use tools like Apache JMeter, k6, or Visual Studio Load Test.\n     - Profile your application using tools like dotTrace or Visual Studio Diagnostic Tools.\n\n---\n\n### 14. **Use Content Delivery Networks (CDNs)**\n   - **Why**: CDNs cache static assets closer to users, reducing latency and server load.\n   - **How**: Serve static files (e.g., images, CSS, JS) through a CDN.\n\n---\n\n### 15. **Optimize Startup and Middleware**\n   - **Why**: Reducing startup time and middleware overhead improves performance.\n   - **How**:\n     - Minimize the number of middleware components.\n     - Use `AddControllers` instead of `AddMvc` if you don't need Razor Pages or Views.\n     - **Example**:\n       ```csharp\n       services.AddControllers();\n       ```\n\n---\n\n### 16. **Use Health Checks**\n   - **Why**: Health checks help monitor the status of your API and dependencies.\n   - **How**: Use the built-in health checks middleware.\n   - **Example**:\n     ```csharp\n     services.AddHealthChecks()\n             .AddDbContextCheck\u003cAppDbContext\u003e();\n\n     app.UseHealthChecks(\"/health\");\n     ```\n\n---\n\n### Summary\nBy following these best practices, you can design high-performance RESTful APIs in .NET Core that are scalable, secure, and maintainable. Focus on asynchronous programming, efficient database access, caching, and monitoring to ensure optimal performance.\n\n\u003cp align=\"right\"\u003e(\u003ca href=\"#readme-top\"\u003eback to top\u003c/a\u003e)\u003c/p\u003e\n\n\u003c!-- LIVE DEMO --\u003e\n\n## 🚀 Live Demo \u003ca name=\"live-demo\"\u003e\u003c/a\u003e\n\n\u003e Add a link to your deployed project.\n\n- [Live Demo Link](https://google.com)\n\n\u003cp align=\"right\"\u003e(\u003ca href=\"#readme-top\"\u003eback to top\u003c/a\u003e)\u003c/p\u003e\n\n\u003c!-- GETTING STARTED --\u003e\n\n## 💻 Getting Started \u003ca name=\"getting-started\"\u003e\u003c/a\u003e\n\nPrerequisites\n\n[.NET SDK](https://dotnet.microsoft.com/download)\n\n[Visual Studio](https://visualstudio.microsoft.com/) with ASP.NET Core workload.\n\n[GitHub Copilot](https://copilot.github.com/) and [IntelliCode](https://visualstudio.microsoft.com/services/intellicode/) installed and configured.\n\n### Prerequisites\n\nIn order to run this project you need:\n\n\u003c!--\nExample command:\n\n```sh\n gem install rails\n```\n --\u003e\n\n### Setup\nEnable AI Tools:\n\nInstall and enable GitHub Copilot and IntelliCode from the Visual Studio Marketplace.\n\nConfigure Copilot with your GitHub account and IntelliCode with your preferences.\nClone this repository to your desired folder:\n\n\u003c!--\nExample commands:\n\n```sh\n  cd my-folder\n  git clone git@github.com:myaccount/my-project.git\n```\n---\u003e\n\nSQlite Database Setup:\nStep 1: create initial migration (Package Manager Console)\n```sh\n  dotnet ef migrations add InitialCreate --project HighPerformance.Persistence\n```\nStep 2: create the folder defined in AppDbContext for database ('C:/Database/')\n\nStep 3: Execute the command to create and update database (Package Manager Console)\n```sh\n  dotnet ef database update --project HighPerformance.Persistence\n```\n### Install\n\nInstall this project with:\nBuild the api project \n\n```sh\n  dotnet build\n  dotnet run \n```\nOpen the URL https://localhost:7001/swagger/index.html to see endpoints\n\n### Usage\n\nTo run the project, execute the following command:\n\n\u003c!--\nExample command:\n\n```sh\n  rails server\n```\n---\u003e\n\n### Run tests\n\nTo run tests, run the following command:\n\n\u003c!--\nExample command:\n\n```sh\n  bin/rails test test/models/article_test.rb\n```\n---\u003e\n\n### Deployment\n\nYou can deploy this project using:\n\n\u003c!--\nExample:\n\n```sh\n\n```\n --\u003e\n\n\u003cp align=\"right\"\u003e(\u003ca href=\"#readme-top\"\u003eback to top\u003c/a\u003e)\u003c/p\u003e\n\n\u003c!-- AUTHORS --\u003e\n\n## 👥 Authors \u003ca name=\"authors\"\u003e\u003c/a\u003e\n\n\u003e Mention all of the collaborators of this project.\n\n👤 **Author1**\n\n- GitHub: [@githubhandle](https://github.com/githubhandle)\n- Twitter: [@twitterhandle](https://twitter.com/twitterhandle)\n- LinkedIn: [LinkedIn](https://linkedin.com/in/linkedinhandle)\n\n👤 **Author2**\n\n- GitHub: [@githubhandle](https://github.com/githubhandle)\n- Twitter: [@twitterhandle](https://twitter.com/twitterhandle)\n- LinkedIn: [LinkedIn](https://linkedin.com/in/linkedinhandle)\n\n\u003cp align=\"right\"\u003e(\u003ca href=\"#readme-top\"\u003eback to top\u003c/a\u003e)\u003c/p\u003e\n\n\u003c!-- FUTURE FEATURES --\u003e\n\n## 🔭 Future Features \u003ca name=\"future-features\"\u003e\u003c/a\u003e\n\n\u003e Describe 1 - 3 features you will add to the project.\n\n- [ ] **[new_feature_1]**\n- [ ] **[new_feature_2]**\n- [ ] **[new_feature_3]**\n\n\u003cp align=\"right\"\u003e(\u003ca href=\"#readme-top\"\u003eback to top\u003c/a\u003e)\u003c/p\u003e\n\n\u003c!-- CONTRIBUTING --\u003e\n\n## 🤝 Contributing \u003ca name=\"contributing\"\u003e\u003c/a\u003e\n\nContributions, issues, and feature requests are welcome!\n\nFeel free to check the [issues page](../../issues/).\n\n\u003cp align=\"right\"\u003e(\u003ca href=\"#readme-top\"\u003eback to top\u003c/a\u003e)\u003c/p\u003e\n\n\u003c!-- SUPPORT --\u003e\n\n## ⭐️ Show your support \u003ca name=\"support\"\u003e\u003c/a\u003e\n\n\u003e Write a message to encourage readers to support your project\n\nIf you like this project...\n\n\u003cp align=\"right\"\u003e(\u003ca href=\"#readme-top\"\u003eback to top\u003c/a\u003e)\u003c/p\u003e\n\n\u003c!-- ACKNOWLEDGEMENTS --\u003e\n\n## 🙏 Acknowledgments \u003ca name=\"acknowledgements\"\u003e\u003c/a\u003e\n\n\u003e Give credit to everyone who inspired your codebase.\n\nI would like to thank...\n[How I Code with GitHub Copilot in Visual Studio 2022 to Boost Productivity Everyday](https://youtu.be/Z6BYhJl9hV8)\nCopilot commads:\n[Get better answers by setting the context for GitHub Copilot Chat in Visual Studio](https://learn.microsoft.com/en-us/visualstudio/ide/copilot-chat-context?view=vs-2022)\nCopilot Documentation:\n[GH Copilot Documentation](https://docs.github.com/en/copilot)\n[Copilot Best Practice](https://www.youtube.com/watch?v=2q0BoioYSxQ)\n\u003cp align=\"right\"\u003e(\u003ca href=\"#readme-top\"\u003eback to top\u003c/a\u003e)\u003c/p\u003e\n\n\u003c!-- FAQ (optional) --\u003e\n\n## ❓ FAQ (OPTIONAL) \u003ca name=\"faq\"\u003e\u003c/a\u003e\n\n\u003e Add at least 2 questions new developers would ask when they decide to use your project.\n\n- **[Question_1]**\n\n  - [Answer_1]\n\n- **[Question_2]**\n\n  - [Answer_2]\n\n\u003cp align=\"right\"\u003e(\u003ca href=\"#readme-top\"\u003eback to top\u003c/a\u003e)\u003c/p\u003e\n\n\u003c!-- LICENSE --\u003e\n\n## 📝 License \u003ca name=\"license\"\u003e\u003c/a\u003e\n\nThis project is [MIT](./LICENSE) licensed.\n\n_NOTE: we recommend using the [MIT license](https://choosealicense.com/licenses/mit/) - you can set it up quickly by [using templates available on GitHub](https://docs.github.com/en/communities/setting-up-your-project-for-healthy-contributions/adding-a-license-to-a-repository). You can also use [any other license](https://choosealicense.com/licenses/) if you wish._\n\n\u003cp align=\"right\"\u003e(\u003ca href=\"#readme-top\"\u003eback to top\u003c/a\u003e)\u003c/p\u003e\n\n\n\n\nYour code is already following a clean architecture approach by using MediatR to decouple the controller from the business logic. However, there are a few improvements and best practices you can consider to make the code more robust, maintainable, and aligned with Clean Architecture principles:\n\n---\n\n### 1. **Use DTOs (Data Transfer Objects) Instead of Exposing Domain Entities**\n \n### 2. **Add Validation for Input Parameters**\n \n### 3. **Use Cancellation Tokens**\n  \n### 4. **Add Pagination for Large Data Sets**\n \n### 5. **Use a Base Controller for Common Functionality**\n \n### 6. **Add Logging**\n\n### 7. **Add Exception Handling**\n\n### 8. **Use Dependency Injection for Validators**\n   - Instead of manually creating validator instances, register them in the DI container and inject them into the controller.\n\n   **Example:**\n   ```csharp\n   services.AddScoped\u003cIValidator\u003cGetProductByIdQuery\u003e, GetProductByIdQueryValidator\u003e();\n   ```\n\n   Inject the validator into the controller:\n   ```csharp\n   private readonly IValidator\u003cGetProductByIdQuery\u003e _validator;\n\n   public ProductsController(IMediator mediator, IValidator\u003cGetProductByIdQuery\u003e validator)\n   {\n       _mediator = mediator;\n       _validator = validator;\n   }\n   ```\n\n---\n\n### Final Improved Code:\n```csharp\n[Route(\"api/[controller]\")]\n[ApiController]\npublic class ProductsController : BaseController\n{\n    private readonly ILogger\u003cProductsController\u003e _logger;\n    private readonly IValidator\u003cGetProductByIdQuery\u003e _validator;\n\n    public ProductsController(IMediator mediator, ILogger\u003cProductsController\u003e logger, IValidator\u003cGetProductByIdQuery\u003e validator) : base(mediator)\n    {\n        _logger = logger;\n        _validator = validator;\n    }\n\n    [HttpGet]\n    public async Task\u003cActionResult\u003cList\u003cProductDto\u003e\u003e\u003e GetProducts([FromQuery] int pageNumber = 1, [FromQuery] int pageSize = 10, CancellationToken cancellationToken = default)\n    {\n        _logger.LogInformation(\"Fetching all products\");\n        var query = new GetProductsQuery { PageNumber = pageNumber, PageSize = pageSize };\n        return await HandleQuery(query, cancellationToken);\n    }\n\n    [HttpGet(\"{id}\")]\n    public async Task\u003cActionResult\u003cProductDto\u003e\u003e GetProductById(int id, CancellationToken cancellationToken = default)\n    {\n        var query = new GetProductByIdQuery { Id = id };\n        var validationResult = await _validator.ValidateAsync(query, cancellationToken);\n\n        if (!validationResult.IsValid)\n        {\n            return BadRequest(validationResult.Errors);\n        }\n\n        return await HandleQuery(query, cancellationToken);\n    }\n}\n```\n\n---\n\nThese improvements will make your code more maintainable, scalable, and aligned with Clean Architecture principles.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fneckerfree%2Fdotnet-highperf-apis","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fneckerfree%2Fdotnet-highperf-apis","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fneckerfree%2Fdotnet-highperf-apis/lists"}