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

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

Ready to Scale? ๐Ÿš€ Build & Run Your .NET Web API in Kubernetes with Docker! ๐Ÿณ Learn How Today

Ready to Scale? ๐Ÿš€ Build & Run Your .NET Web API in Kubernetes with Docker! ๐Ÿณ Learn How Today! Introduction Hello, Netcode-Hub community! ๐Ÿ‘‹ Frederick is here with another exciting lesson for you, we're diving into the world of Kubernetes and Docker, specifically focusing on how to build and run your .NET Web API application in Kubernetes using Docker. If you've been using Docker Compose to manage your containerized applications, you're already familiar with the convenience it brings. However, as your applications grow and require more advanced orchestration capabilities, Kubernetes becomes a powerful ally. In this section, I'll walk you through why you should consider Kubernetes over Docker Compose for orchestrating your applications, and we'll set up a practical scenario to highlight the benefits of using Kubernetes. Why Choose Kubernetes Over Docker Compose? Kubernetes and Docker Compose both serve the purpose of managing containerized applicati...

Build Zoom Cloned with .NET 9 Blazor & Web API - Create Admin Dashboard and Meeting Components๐Ÿš€