Filter vs Middleware in .NET Core

 "Filter vs Middleware in .NET Core 

📌 Middleware 

"Middleware runs for every HTTP request — even before the controller is selected.

Use it for global logic like logging, authentication, or CORS.

And in .NET 6 or later, just add it directly in Program.cs like this:"


app.Use(async (context, next) => {

    Console.WriteLine("In Middleware");

    await next();

});

 

📌 Filters 

"Filters work only inside the MVC pipeline — after the route hits your controller.

Use them for things like input validation, logging, or modifying responses.

Just create a class like this:"

public class LogActionFilter : ActionFilterAttribute {

    public override void OnActionExecuting(ActionExecutingContext context) {

        Console.WriteLine("In Filter");

    }

}

 

MVC 

MVC means Model-View-Controller — the structure of most .NET apps.

Middleware runs before MVC, filters run inside MVC."

 

🎯 Call-to-Action

"Global logic? Use Middleware. Controller logic? Use Filters.












Post a Comment

0 Comments