Category - Programmatically

API Versioning with .NET 8.0
Feb 11, 2025

Why API Versioning? API versioning allows developers to: Introduce new API features without breaking existing clients. Deprecate older API versions in a controlled manner. Provide clear communication about supported versions.   With .NET 8.0, setting up API versioning is straightforward and efficient. Let’s explore how to implement it. In the Program.cs file, configure services for controllers and API versioning: using Microsoft.AspNetCore.Mvc; var builder = WebApplication.CreateBuilder(); // Add services for controllers and API versioning builder.Services.AddControllersWithViews(); builder.Services.AddApiVersioning(o => { o.ReportApiVersions = true; // Include version information in responses }); var app = builder.Build(); // Map default controller route app.MapDefaultControllerRoute(); app.Run(); Nuget Package Name : Microsoft.AspNetCore.Mvc.Versioning Implementing a Versioned Controller Define a versioned controller to handle API requests. Use the ApiVersion attribute to specify the API version and the route. [ApiVersion("1.0")] [ApiVersion("2.0")] [Route("api/v{version:apiVersion}/[controller]")] [ApiController] public class HelloWorldController : ControllerBase { [HttpGet] public IActionResult Get(ApiVersion apiVersion) => Ok(new { Controller = GetType().Name, Version = apiVersion.ToString(), Message = "This is version 1 of the API" }); [HttpGet, MapToApiVersion("2")] public IActionResult GetV2(ApiVersion apiVersion) => Ok(new { Controller = GetType().Name, Version = apiVersion.ToString(), Message = "This is version 2 of the API" }); } Key Points in the Code ApiVersion("1"): Specifies that this controller handles API version 1. Route("api/v{version:apiVersion}/[controller]"): Dynamically includes the API version in the route. ApiVersion** parameter**: Captures the requested version and includes it in the response. Endpoint : GET http://localhost:51346/api/v1/HelloWorld Response : {     "Controller": "HelloWorldController",     "Version": "1",     "Message": "This is version 1 of the API" } Endpoint : GET http://localhost:51346/api/v2/HelloWorld Response : {     "Controller": "HelloWorldController",     "Version": "2",     "Message": "This is version 2 of the API" } Conclusion API versioning in .NET 8.0 is a simple yet powerful feature for managing evolving APIs. By integrating AddApiVersioning and leveraging attributes like ApiVersion and Route, developers can efficiently support multiple API versions without sacrificing maintainability. If you have further questions or insights, feel free to share them in the comments!

Top Useful C# .NET Snippets
Jun 07, 2024

In this blog, I will explore the top useful C# .NET snippets that every developer should have in their arsenal.  From object initialization syntax to dictionary initialization, these snippets cover a wide range of functionalities that will help you streamline your C# development process. Object Initialization Syntax - By using object initialization syntax, you can quickly create and initialize objects without the need for multiple lines of code. public class Product { public string Name { get; set; } public decimal Price { get; set; } } var product = new Product { Name = "Mouse", Price = 999.00 }; Enumerable.Range Method - This snippet simplifies the process of iterating over a range of numbers in a concise and readable manner. foreach (var number in Enumerable.Range(1, 10)) { Console.WriteLine(number); } Conditional Ternary Operator - By using the conditional ternary operator, you can streamline conditional checks and make your code more compact and readable. int time = 7; var result = (time < 5) ? "Weekend" : "Working"; Console.WriteLine(result); Task.WhenAll Method - With Task.WhenAll, you can improve the performance of your asynchronous operations by running them concurrently. async Task DownloadAllAsync(List<string> urls) { var tasks = urls.Select(url => DownloadAsync(url)).ToArray(); await Task.WhenAll(tasks); } async Task DownloadAsync(string url) { Console.WriteLine($"Downloading from {url}"); } Null-Conditional Operator - By using the null-conditional operator, you can handle null values gracefully and prevent runtime exceptions in your code. string firstName = person?.FirstName ?? "Unknown"; Console.WriteLine(firstName); LINQ Query Syntax - By leveraging LINQ query syntax, you can write complex queries on collections with ease and readability. var scores = new int[] { 90, 100, 82, 89, 92 }; var highScores = from score in scores where score >= 90 select score; foreach (var score in highScores) { Console.WriteLine(score); } Using Statement - The using statement is essential for handling disposable objects and preventing resource leaks in your code. using (var streamReader = new StreamReader(@"C:\file.txt")) { string content = streamReader.ReadToEnd(); Console.WriteLine(content); } Expression-Bodied Members - By using expression-bodied members, you can make your code more concise and expressive, especially for simple properties and methods.   public class Person { public string FirstName { get; set; } public string LastName { get; set; } public string FullName => $"{FirstName} {LastName}"; // Fullname directly dynamically set at model level. } Dictionary Initialization - Dictionary initialization simplifies the process of populating key-value pairs in a dictionary with a clean and readable syntax. var capitals = new Dictionary<string, string> { ["USA"] = "Washington, D.C.", ["Japan"] = "Tokyo", ["India"] = "Delhi" };   Appending an Element to a List - C# offers numerous methods for adding items to lists. For instance, the widely-used Add() method is available. However, there are plenty of other options as well. Here are five: // Statically defined list List<int> myList = new List<int> {2, 5, 6}; // Appending using Add() myList.Add(5); // [2, 5, 6, 5] // Appending using AddRange() myList.AddRange(new List<int> {9}); // [2, 5, 6, 5, 9] // Appending using Insert() myList.Insert(myList.Count, -4); // [2, 5, 6, 5, 9, -4] // Appending using InsertRange() myList.InsertRange(myList.Count, new List<int> {3}); // [2, 5, 6, 5, 9, -4, 3] // To Check if a List Is Empty List<int> myList = new List<int>(); // Check if a list is empty by its Count if (myList.Count == 0) { // the list is empty } // Check if a list is empty by its type flexibility **preferred method** if (!myList.Any()) { // the list is empty } String Interpolation (Formatting a String) - Oftentimes, we need to format strings to display information in a more readable or structured manner. Here are some options: string name = "Himanshu"; int age = 25; // String formatting using concatenation Console.WriteLine("My name is " + name + ", and I am " + age + " years old."); // String formatting using composite formatting Console.WriteLine("My name is {0}, and I am {1} years old.", name, age); // String formatting using interpolation (C# 6.0+) Console.WriteLine($"My name is {name}, and I am {age} years old"); These are but a small example of the power and flexibility that C# and .NET bring to the table.Thank you for reading! We hope these C# .NET snippets will help you streamline your development process and boost your productivity.

Simplified Swagger Integration in .NET Core
Feb 22, 2024

Introduction: In the realm of modern APIs, the provision of clear and comprehensive documentation plays a pivotal role in facilitating developer adoption and ensuring efficient utilization. Swagger, aligned with the OpenAPI Initiative, stands out as a prominent solution, offering machine-readable documentation and a user-friendly interactive interface. In this guide, we'll delve into the seamless integration of Swagger into your .NET Core API. Step 1: Install the necessary packages Add Swashbuckle.AspNetCore NuGet package to a project: dotnet add package Swashbuckle.AspNetCore Add Swashbuckle.AspNetCore.SwaggerUI NuGet package to a project: dotnet add package Swashbuckle.AspNetCore.SwaggerUI Step 2: Add services in program.cs In the program.cs file, include the following service additions: builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); Additionally, add middleware in program.cs to enable Swagger in the development environment:   if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } Step 3: Run the API project and access the Swagger UI at: https://your-api-base-url/swagger Ensure the API project is running, and navigate to the provided URL to explore and interact with the Swagger UI seamlessly. Step 3:  Execute the APIs and test.  

magnusminds website loader