Ana Sayfa Hakkımda Dersler Blog MikrofondaOn The Mic İletişim Projeler Yakında
DerslerLessons ASP.NET CORE · C#

ASP.NET Core — Filter vs Middleware ASP.NET Core — Filter vs Middleware

9 dk okuma 9 min read · Emre Ulutabak
1
Büyük resim The big picture

ASP.NET Core uygulamasında bir istek geldiğinde bu istek hemen controller içine düşmez. Önce uygulamanın request hattından geçer, sonra uygunsa controller ve action seviyesine ulaşır.

Bu yüzden bazı kontroller en dış katmanda yapılır, bazıları ise action'a daha yakın noktada yapılır. İşte middleware ve filter farkı tam burada başlar.

In an ASP.NET Core application, a request does not jump directly into the controller. It first passes through the request pipeline, and only then reaches the controller and action if allowed.

That is why some checks belong to the outer layer, while others belong closer to the action. This is exactly where the difference between middleware and filters begins.

text
Browser -> Middleware -> Controller -> Action -> Response
💡
Middleware daha dış katmandır. Filter ise MVC tarafında, action'a daha yakın çalışır. Middleware lives in the outer layer. A filter works closer to the action inside MVC.
2
Middleware nedir? What is middleware?

Middleware, uygulamaya gelen neredeyse her isteğin geçtiği genel kontrol katmanıdır. Request daha controller'a ulaşmadan önce burada karşılanır.

Kimlik doğrulama, yetkilendirme, logging, global hata yönetimi gibi sistem genelini ilgilendiren konular burada çözülür.

Kısacası middleware şunu sorar: Bu istek sisteme devam edebilir mi?

Middleware is the general control layer that almost every incoming request passes through. The request is handled here before it ever reaches the controller.

Authentication, authorization, logging, and global exception handling are typical responsibilities of this layer.

In short, middleware asks: Can this request continue through the system?

3
Filter nedir? What is a filter?

Filter ise MVC tarafında, controller ve action seviyesine daha yakın çalışan bir kontroldür. Her request için değil, sadece ilgili controller veya action devreye girdiğinde çalışır.

Bu yüzden iş kuralına yakın kontroller için çok uygundur. Mesela aktif plan kontrolü, belirli bir feature erişimi veya action'a özel bir kısıt burada mantıklı olabilir.

Filter daha çok şunu sorar: Bu kullanıcı bu action'ı çalıştırabilir mi?

A filter works on the MVC side, much closer to the controller and action. It does not run for every request, only when the related controller or action is involved.

That makes it a strong fit for checks that are close to business rules, such as active-plan validation, feature access, or action-specific restrictions.

A filter usually asks: Can this user execute this action?

4
Hikaye: Banlanan kullanıcı Story: The banned user

Bir yazılım sistemi düşün. Yönetici panelinden bir kullanıcı banlanıyor. Artık o kişinin sistemde dolaşmasını istemiyorsun.

Kullanıcı o anda giriş yapmış olsa bile, en ufak sayfa yenilemede veya yeni istekte sistem onu fark etmeli. Yani sadece belirli bir controller değil, tüm uygulama seviyesinde bu durum hissedilmeli.

İşte bu senaryo filter'dan çok middleware kokar. Çünkü burada amaç belirli bir action'ı engellemek değil, kullanıcının sistemde ilerlemesini genel olarak durdurmaktır.

Imagine a software system where an admin bans a user from the admin panel. You no longer want that person moving around inside the application.

Even if the user is already logged in, the system should notice it on the next refresh or request. This should be enforced across the whole application, not just inside a specific controller.

This scenario smells much more like middleware than a filter. The goal is not to block one action, but to stop the user from continuing through the system at all.

5
Neden burada middleware? Why middleware here?

Çünkü ban kontrolü sistem geneline ait bir güvenlik kararıdır. Kullanıcıyı bir yerde durdurup başka yerde serbest bırakmak istemezsin. Banlandıysa, her yeni request'te bu bilgi dikkate alınmalıdır.

Middleware bu iş için uygundur çünkü controller'a gelmeden çalışır. Kullanıcı banlıysa oturumu kapatılabilir, erişimi kesilebilir ve uygun sayfaya yönlendirilebilir.

Yani middleware burada “bu kullanıcı bu action'a girebilir mi?” diye değil, “bu kullanıcı sistemde kalabilir mi?” diye düşünür.

Because a ban check is a system-wide security decision. You do not want the user blocked in one place but still free to move elsewhere. If the user is banned, that fact should be considered on every new request.

Middleware fits this well because it runs before the controller. If the user is banned, the session can be closed, access can be denied, and the user can be redirected appropriately.

So middleware here is not asking “Can this user access this action?” but rather “Can this user remain in the system at all?”

💡
Global güvenlik ve sistem seviyesi erişim kararları çoğu zaman middleware tarafına daha uygundur. Global security and system-level access decisions usually belong more naturally in middleware.
6
Filter ne zaman daha doğru? When is a filter the better choice?

Her kontrol middleware olmamalıdır. Mesela bir kullanıcının aktif planı var mı, belirli bir ürüne erişebilir mi, bu action sadece premium üyeler için mi gibi kurallar daha çok action seviyesine yakındır.

Bunlar her request'te değil, sadece ilgili controller veya action kullanıldığında kontrol edilmelidir. İşte burada filter daha temiz ve daha isabetli bir çözümdür.

Yani ban gibi sistemsel kararlar middleware'a, iş kuralına yakın kararlar ise çoğu zaman filter'a daha çok yakışır.

Not every check should become middleware. For example, whether a user has an active plan, can access a specific product, or is allowed into a premium-only action are checks much closer to the action level.

These should not run for every request, only when the related controller or action is being used. That is where a filter becomes the cleaner and more precise solution.

So system-level decisions like bans often belong in middleware, while business-rule checks usually fit filters better.

7
Kısa middleware örneği A short middleware example

Aşağıdaki örnekte kullanıcı giriş yapmışsa ban durumu kontrol ediliyor. Eğer banlıysa sistem kullanıcıyı oturumdan çıkarıyor ve özel bir sayfaya yönlendiriyor.

Böylece kişi bir sonraki refresh anında bile sistem dışında kalmış oluyor.

In the example below, the middleware checks the ban status of an authenticated user. If the user is banned, the system signs them out and redirects them to a dedicated page.

This means the user is pushed out of the system even on the very next refresh.

csharp
public class BanCheckMiddleware
{
    private readonly RequestDelegate _next;

    public BanCheckMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        var user = context.User;

        if (user.Identity != null && user.Identity.IsAuthenticated)
        {
            var isBanned = false;

            if (isBanned)
            {
                await context.SignOutAsync();
                context.Response.Redirect("/Account/Banned");
                return;
            }
        }

        await _next(context);
    }
}
💡
Middleware akışı erken kesebilir. Bu sayede request controller'a hiç ulaşmadan durdurulabilir. Middleware can stop the flow early, preventing the request from ever reaching the controller.
8
Altın kurallar Golden rules

Bir kontrolü nereye koyacağını seçerken şu soruyu sor: Bu kural sistem genelini mi ilgilendiriyor, yoksa belirli action'ları mı?

Eğer cevap tüm sistemi ilgilendiriyorsa middleware düşün. Eğer cevap belirli controller veya action'lara yakınsa filter düşün.

When deciding where a check belongs, ask yourself: does this rule concern the whole system, or only certain actions?

If it concerns the whole system, think middleware. If it is closer to specific controllers or actions, think filter.

💡
Middleware dış kapıdır, filter ise iç kapıya daha yakındır. Middleware is the outer gate, while a filter stands closer to the inner gate.
💡
Ban, authentication, logging gibi konular middleware'a yakışır. Concerns like bans, authentication, and logging are a natural fit for middleware.
💡
Plan, stok, feature erişimi gibi action'a yakın kurallar filter için daha uygundur. Rules like plans, stock checks, and feature access fit filters better.
💡
Her şeyi middleware yapmak da, her şeyi filter yapmak da doğru değildir. Turning everything into middleware or everything into filters is not the right approach.
MİNİ QUIZ MINI QUIZ
Aşağıdakilerden hangisi daha doğru bir eşleştirmedir? Which of the following is the more correct pairing?
Ban kontrolü → Filter Ban check → Filter
Sistem genelinde oturum düşürme → Middleware System-wide forced sign-out → Middleware
Her action'a özel iş kuralı → Middleware Action-specific business rule → Middleware
Ürün stok kontrolü → Her request'te middleware Product stock check → Middleware on every request