Skip to main content

Build Zoom Cloned with .NET 9 Blazor & Web API - Build Backend API๐Ÿš€

Goodbye Complexity๐Ÿ™‹‍♂️, Hello Middleware Magic๐Ÿ‘‹! Supercharge Your .NET Web API Like a Pro!๐Ÿš€๐Ÿ”ฅ


 We're diving into a crucial aspect of .NET Web API development – Middleware. If you want to enhance your APIs with powerful functionalities, you've come to the right place! ๐ŸŽ‰

 From handling requests and responses to logging and authentication, middleware is the unsung hero of Web API. Stick around to learn why it's useful, when to use it, and how to create your own middleware using Request Delegate and the IMiddleware interface!


 # What is Middleware?

 Middleware is a piece of software that intercepts HTTP requests and responses in the pipeline. It allows you to handle cross-cutting concerns like logging, authentication, and error handling.


 # Why should you use Middleware?

 It allows for a clean separation of concerns, reusability of code, and a centralized way to handle common functionalities. You should consider using middleware when you need to handle tasks like logging, authentication, error handling, and even performance monitoring.


 #  Middleware using Request Delegate

 public class AuthorizationMiddleware : IMiddleware
 {
     public async Task InvokeAsync(HttpContext context, RequestDelegate next)
     {
         var authState = context.Request.Headers["AuthState"].FirstOrDefault();
         if (Equals(authState, "Authenticated"))
         {
             await next(context);
         }
         else
         {
             var error = new ProblemDetails()
             {
                 Title = $"AuthState={authState}",
                 Status = StatusCodes.Status401Unauthorized,
                 Detail = "You are not allowed to access"
             };
             context.Response.ContentType = "application/json";
             await context.Response.WriteAsync(JsonSerializer.Serialize(error));
             return;
         }
     }
 }



 public class AuthenticationMiddleware(RequestDelegate next)
 {
     public async Task InvokeAsync(HttpContext context)
     {
         var authHeader = context.Request.Headers["AuthState"].FirstOrDefault();
         if (!string.IsNullOrEmpty(authHeader))
         {
             await next(context);
         }
         else
         {
             var error = new ProblemDetails()
             {
                 Title = "No authentication Header Found",
                 Status = StatusCodes.Status404NotFound,
                 Detail = "No authentication Header [AuthState] found"
             };
             context.Response.ContentType = "application/json";
             await context.Response.WriteAsync(JsonSerializer.Serialize(error));
             return;
         }
     }
 }

 public class AuthorizationMiddleware : IMiddleware
 {
     public async Task InvokeAsync(HttpContext context, RequestDelegate next)
     {
         var authState = context.Request.Headers["AuthState"].FirstOrDefault();
         if (Equals(authState, "Authenticated"))
         {
             await next(context);
         }
         else
         {
             var error = new ProblemDetails()
             {
                 Title = $"AuthState={authState}",
                 Status = StatusCodes.Status401Unauthorized,
                 Detail = "You are not allowed to access"
             };
             context.Response.ContentType = "application/json";
             await context.Response.WriteAsync(JsonSerializer.Serialize(error));
             return;
         }
     }
 }

# Create Simple Middleware

  app.Use(async (context, next) =>
{
    Console. WriteLine($"Request: {context.Request.Method} {context.Request.Path}");
    await next();

});

# Use All Middlewares

builder.Services.AddTransient<AuthorizationMiddleware>();
app.UseMiddleware<AuthenticationMiddleware>();
app.UseMiddleware<AuthorizationMiddleware>();
app.Use(async (context, next) =>
{
    Console.WriteLine($"Request: {context.Request.Method} {context.Request.Path}");
    await next();

});
app.MapControllers();

# Why Choose Request Delegate vs. IMiddleware?

Use Request Delegate for simple, quick middleware where dependency injection is not needed. Opt for IMiddleware when you need a more organized structure and want to leverage dependency injection for your middleware.


# Summary

To wrap it up, middleware is a powerful tool in your Web API arsenal. It helps you manage common tasks efficiently. Whether you choose Request Delegate or IMiddleware depends on your specific needs. Understanding and implementing middleware will take your API development to the next level! ๐Ÿš€


# Here's a follow-up section to encourage engagement and support for Netcode-Hub:

๐ŸŒŸ Get in touch with Netcode-Hub! ๐Ÿ“ซ

1. GitHub: [Explore Repositories] ๐ŸŒ

2. Twitter: [Stay Updated] ๐Ÿฆ

3. Facebook: [Connect Here]๐Ÿ“˜

4. LinkedIn: [Professional Network]๐Ÿ”—

5. Email: [business.netcodehub@gmail.com] ๐Ÿ“ง

# ☕️ If you've found value in Netcode-Hub's work, consider supporting the channel with a coffee!

1. Buy Me a Coffee: [Support Netcode-Hub] ☕️


Comments

Popular Posts

Flight Reservation Project Using .NET 9 Microservices

1. Understanding Flight Reservation Basics Feature: Search Flights: User inputs departure and destination cities, travel dates, number of passengers, and flight class (economy, business, etc.). Application queries available flights and displays results with pricing, duration, stops, and airline details. Feature: Select Flight: User selects a flight from the search results. Options for extras (e.g., seat selection, meals, baggage) are often offered at this stage. Enter Passenger Details: User provides traveler information such as name, age, passport (if international), contact details, etc. Payment and Booking Confirmation: User makes payment via credit card, debit card, PayPal, or other payment methods. Booking is confirmed, and a ticket (e-ticket) is generated. Feature: Ticket Issuance: E-ticket is sent to the user via email or displayed on the web app. The ticket includes a booking reference, flight details, and passenger information. Manage Booking: User can view or modify bookings ...

Complete Employee Management System | .NET 8 Blazor Wasm & Web API - Perform CRUD, Print, PDF etc..

.NET 8 Clean Architecture with Blazor CRUD, JWT & Role Authorization using Identity & Refresh Token๐Ÿ”ฅ