Tag - WebAPI

Comparison between Minimal APIs and Controllers
Jun 17, 2024

Introduction  In the ever-evolving landscape of web development, simplicity is key. Enter Minimal APIs in ASP.NET Core, a lightweight and streamlined approach to building web applications. In this detailed blog, we'll explore the concept of Minimal APIs, understand why they matter, and walk through their implementation in ASP.NET Core.    When to Use Minimal APIs?  Minimal APIs are well-suited for small to medium-sized projects, microservices, or scenarios where a lightweight and focused API is sufficient. They shine in cases where rapid development and minimal ceremony are top priorities.  You can find in this blog <link> how to create minimal api.  I am directly showing the comparison between MinimalAPI and controller.    Controllers: Structured and Versatile  Controllers, deeply rooted in the MVC pattern, have been a cornerstone of ASP.NET API development for years. They provide a structured way to organize endpoints, models, and business logic within dedicated controller classes.  Let's consider an example using Microsoft.AspNetCore.Mvc; namespace MinimalAPI.Controllers { [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; } [HttpGet(Name = "GetWeatherForecast")] public IEnumerable<WeatherForecast> Get() { return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)), TemperatureC = Random.Shared.Next(-20, 55), Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray(); } } } Advantages of Controllers in Action  Structure and Organization: Controllers offer a clear structure, separating concerns and enhancing maintainability.  Flexibility: They enable custom routes, complex request handling, and support various HTTP verbs.  Testing: Controllers facilitate unit testing of individual actions, promoting a test-driven approach   Minimal APIs: Concise and Swift  With the advent of .NET 6, Minimal APIs emerged as a lightweight alternative, aiming to minimize boilerplate code and simplify API creation.  Here's an example showcasing Minimal APIs.  using MinimalAPI; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); var app = builder.Build(); app.MapGet("/GetWeatherForecast", () => { var rng = new Random(); var summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; var weatherForecasts = Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index).Date, TemperatureC = rng.Next(-20, 55), Summary = summaries[rng.Next(summaries.Length)] }).ToArray(); return Results.Ok(weatherForecasts); }); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run(); Advantages of Minimal APIs in Focus  Simplicity: Minimal APIs drastically reduce code complexity, ideal for smaller projects or rapid prototyping.  Ease of Use: They enable quick API creation with fewer dependencies, accelerating development cycles.  Potential Performance Boost: The reduced overhead might lead to improved performance, especially in smaller applications.    What you choose between MinimalAPI and Controller?  Choosing between Controllers and Minimal APIs hinges on various factors.  Project Scale: Controllers offer better organization and structure for larger projects with intricate architectures.  Development Speed: Minimal APIs shine when speed is crucial, suitable for rapid prototyping or smaller projects.  Team Expertise: Consider your team's familiarity with MVC patterns versus readiness to adopt Minimal APIs.    Conclusion  The decision between Controllers and Minimal APIs for .NET APIs isn't about one being superior to the other. Rather, it's about aligning the choice with the project's specific needs and constraints. Controllers offer robustness and versatility, perfect for larger, complex projects. On the other hand, Minimal APIs prioritize simplicity and rapid development, ideal for smaller, more straightforward endeavours. 

How to create MinimalAPI in .NET
May 27, 2024

What is MinimalAPI?  Minimal APIs are a simplified way of building web APIs in ASP.NET Core. They are designed for scenarios where you need a quick and minimalistic approach to expose endpoints without the overhead of a full-fledged MVC application.    Why Minimal APIs?  Efficiency: Write less, do more. A mantra for the modern developer.  Performance: They’re lean, mean, and fast, perfect for high-performance scenarios.  Ease of Use: New to .NET? No problem! Minimal APIs are accessible and easy to grasp.  Flexibility: Simplicity doesn’t mean limited. From microservices to large-scale applications, they’ve got you covered.    How Minimal APIs Work?  Minimal APIs leverage the WebApplication class to define routes and handle HTTP requests. They rely on a functional approach, allowing developers to define endpoints using lambda expressions.    Limitations of Minimal API  No support for filters: For example, no support for IAsyncAuthorizationFilter, IAsyncActionFilter, IAsyncExceptionFilter, IAsyncResultFilter, and IAsyncResourceFilter.  No support for model binding, i.e. IModelBinderProvider, IModelBinder. Support can be added with a custom binding shim.  No support for binding from forms. This includes binding IFormFile. We plan to add support for IFormFile in the future.  No built-in support for validation, i.e. IModelValidator  No support for application parts or the application model. There's no way to apply or build your own conventions.  No built-in view rendering support. We recommend using Razor Pages for rendering views.  No support for JsonPatch  No support for OData    How to create a Minimal API?  Creating a Minimal API closely mirrors the traditional approach, so you should encounter no significant challenges. It is a straightforward procedure that can be accomplished in just a few easy steps.  Let's get started:  Step 1:   Open Visual Studio and select the ASP.NET Core Web API.  Provide a preferred name for your project and select the location where you wish to store it.  For the final step, choose the targeted framework, ensure that the "Configure for HTTPS" and "Enable OpenAPI support" checkboxes are checked, and, most importantly, leave the checkbox "Use controllers (uncheck to use Minimal API)" unchecked. Then, click the "Create" button.  Step 2:  Create one class with two fields and create one list class with some static values.  namespace MinimalAPI { public class Student { public int Id { get; init; } public string Name { get; set; } } public static class StudentList { public static List<Student> student = new List<Student>() { new Student() { Id = 1, Name = "Test1", }, new Student() { Id = 2, Name = "Test2", }, new Student() { Id = 3, Name = "Test3", } }; } } Now add register new endpoint in Program.cs file.  app.MapGet("GetAllStudent", () => StudentList.student); Run the project and see the output.  I have added Create, Update and Delete student endpoint. See the full code below.  using MinimalAPI; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); var app = builder.Build(); // GetAll app.MapGet("GetAllStudent", () => StudentList.student); // GetById app.MapGet("GetByStudentId/{id}", (int id) => StudentList.student.FirstOrDefault(user => user.Id == id)); // Create app.MapPost("CreateStudent", (Student student) => StudentList.student.Add(student)); // Update app.MapPut("UpdateStudent/{id}", (int id, Student student) => { Student currentStudent = StudentList.student.FirstOrDefault(user => user.Id == id); currentStudent.Name = student.Name; }); // Delete app.MapDelete("DeleteStudent/{id}", (int id) => { var student = StudentList.student.FirstOrDefault(user => user.Id == id); StudentList.student.Remove(student!); }); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run(); Run the code and see the output. Conclusion:  Minimal APIs in ASP.NET Core, introduced in .NET 6, offer a simplified and concise approach to building lightweight HTTP services, reducing boilerplate and emphasizing convention-based routing. While ideal for rapid development of small to medium-sized APIs, they lack advanced features found in traditional ASP.NET Core applications and may not be suitable for complex scenarios. 

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.  

API Security with Swagger Customization
Jan 02, 2024

In this blog, I will be sharing insights on how to effectively manage Conditional Authorization and Swagger Customization.   Case 1   I'm currently working on a problem our QA team found while testing our website. Specifically, there's an issue with one of the features in the application that uses an API. In the QA environment, we need to allow access without authentication, but in the production environment, authentication is required. To fix this, I added a feature called Conditional Authorize Attribute with help of Environment Variable. This feature lets us control access to the API based on the environment. It allows anonymous access when necessary.   In my situation, I've added a environment variable setting called "ASPNETCORE_ENVIRONMENT" to "QA" in the testing site's pipeline. Because of this, I can use the API on the QA server without requiring authentication.   This method also helps specific authorization rules for the API based on the environment.   Case 2 Additionally, I've added Swagger requests into a value object to meet specific requirements on swagger. By extending the Swashbuckle Swagger IOperationFilter, I integrated logic tailored to our needs. This approach allows us to customize requests in Swagger for all APIs directly.   Furthermore, I've implemented a middleware designed to handle responses and here's how it works. In my case, there are three kinds of response class in my code that specify the response type (like ApiErrorResponse, ValidatorResponse, ResponseModel). According to the requirements, when we get a 200-status code with the correct response class model, I need to wrap the response object in a value format. I created a middleware for this. It figures out which endpoint we're dealing with through the HttpContext. Using that endpoint, I grab the metadata related to the ProducesResponseTypeAttribute class and check for a status code of OK (Metadata Extraction). If I manage to get the metadata with a status code of 200, I include that response in value format. Otherwise, I stick with the same model response. This helps you to modify the response as per needed outcome. These implementations provide a flexible solution for conditionally authorizing API access and wrapping request/response in an object according to specified requirements.

magnusminds website loader