<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by emrecglar on Medium]]></title>
        <description><![CDATA[Stories by emrecglar on Medium]]></description>
        <link>https://medium.com/@emrecglar?source=rss-9d515996c3ca------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by emrecglar on Medium</title>
            <link>https://medium.com/@emrecglar?source=rss-9d515996c3ca------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 02:37:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@emrecglar/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[pip yerine uv kullanma]]></title>
            <link>https://emrecglar.medium.com/pip-yerine-uv-kullanma-a98efd8d528c?source=rss-9d515996c3ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/a98efd8d528c</guid>
            <dc:creator><![CDATA[emrecglar]]></dc:creator>
            <pubDate>Thu, 03 Sep 2026 15:19:08 GMT</pubDate>
            <atom:updated>2026-09-03T15:30:04.478Z</atom:updated>
            <content:encoded><![CDATA[<p>uv install docs: <a href="https://docs.astral.sh/uv/getting-started/installation/">https://docs.astral.sh/uv/getting-started/installation/</a></p><p>uv docs: <a href="https://www.youtube.com/redirect?event=video_description&amp;redir_token=QUM4Zm9rU1B4Z0dTeVYxalNMQzl1RTdCYzdLRXxBTl9pYzRmTVFEelFZdURJcUhJa1pXQXYxZmY0MmExNUVjWjdSeFk4SXNJdzRiSF9iNlJDZ2c3NUIwb21vM1J6UVdVbUcwTnp6RGhnbHNmM25DaDJFRTNxNklXTThkZnZRb0ln&amp;q=https%3A%2F%2Fdocs.astral.sh%2Fuv%2F&amp;v=6pttmsBSi8M">https://docs.astral.sh/uv/</a></p><p>uv python install 3.8 gibi komutlarlar python sürümü yükleyebiliriz.</p><p>uv python uninstall dersek var olan sürümü silebiliriz.</p><p>uv run app.py ile app.py dosyasını çalıştırabiliriz. veya uv run — python 3.9.21 app.py dersek 3.9.21 versiyonu ile çalıştırırız istediğimizi.</p><p>bulunduğumuz dosyada uv init . dersek eğer o zaman bize lazımlık bazı dosyaları otomatik getirir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/185/1*__eFmLCfDlHUU8J2_c4ttQ.png" /><figcaption>otomatik getirdikleri .toml dosyası requirements.txt’ye eşdeğer gibidir daha detaylıdır. dependencies kısmında bağımlılıklar vs vardır.</figcaption></figure><p>uv add requests dersek mesela o kütüphane .toml’a gelir ve yüklenir. veya istediğimiz versiyonu seçebiliriz. uv add requests == 2.32.3 gibi</p><p>uv remove requests dersek örnek olarak istediğimiz dependenciesi kaldırabiliriz.</p><p>uv add python-dotenv ile .venv eklemesi yapabiliriz.</p><p>.python-version dosyası ile istediğimiz python sürümünü kullanabiliriz.</p><p>ve mesela .toml dosyasında dependencies kısmına elle bir kütüphane girdik sonra uv run main.py veya istediğimiz bir .py dosyasını çalıştırmaya kalktığımızda bunu yükler ve öyle çalıştırır .venv içerisine yükleme yapar.</p><p>eğer uv sync dersek o zaman bu komut girildikten sonra dependencieslerde bir değişim yaptığımızda otomatik olarak .venv etkilenecek güncellemeye göre.</p><p>uv pip dersek eğer o zaman projeye pip ile devam edebiliriz demektir.</p><p>uv lock ile uv.lock dosyasını manuel olarak oluşturabiliriz.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a98efd8d528c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Singleton ve pool]]></title>
            <link>https://emrecglar.medium.com/singleton-ve-pool-c4c46945f466?source=rss-9d515996c3ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4c46945f466</guid>
            <dc:creator><![CDATA[emrecglar]]></dc:creator>
            <pubDate>Sun, 12 Apr 2026 06:56:23 GMT</pubDate>
            <atom:updated>2026-04-12T06:56:23.210Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Thread-Safe (İş Parçacığı Güvenli) Singleton</h3><p>Uygulamanız aynı anda birden fazla iş parçacığı (thread) çalıştırıyorsa, standart bir Singleton çökebilir. Neden mi? Çünkü iki farklı thread <strong>aynı milisaniye içinde</strong> nesnenin olup olmadığını kontrol edip (ikisi de None görür) iki tane farklı nesne yaratabilir. Bu da Singleton kuralını bozar.</p><p>Bunu engellemek için Python’daki threading.Lock() mekanizmasını kullanarak kapıya bir <strong>kilit</strong> asarız.</p><p><strong>Kod Örneği (Çift Kontrollü Kilit Mekanizması):</strong></p><pre>import threading<br>class ThreadSafeSingleton:<br>    _instance = None<br>    _lock = threading.Lock() # Kilit objemizi yaratıyoruz<br>def __new__(cls):<br>        # 1. Kontrol: Eğer nesne zaten varsa hiç kilit mekanizmasıyla vakit kaybetme<br>        if cls._instance is None: <br>            <br>            # Nesne yoksa kapıyı kilitle. Diğer thread&#39;ler burada beklemek zorunda kalır.<br>            with cls._lock:<br>                <br>                # 2. Kontrol: Kapıda beklerken başka bir thread benden önce içeri girip nesneyi yaratmış olabilir mi?<br>                if cls._instance is None:<br>                    cls._instance = super(ThreadSafeSingleton, cls).__new__(cls)<br>                    # Sadece ilk giren thread burayı çalıştırır.<br>                    <br>        return cls._instance</pre><p><strong>Nerede Kullanılır:</strong> Loglama yöneticileri, ortam değişkenlerini (environment variables / config) okuyan sınıflar veya donanım portlarına (örneğin seri port) tekil erişim gereken yerlerde idealdir.</p><h3>2. Veritabanı Bağlantı Havuzu (Connection Pool)</h3><p>Veritabanları için sadece Singleton kullanmak her zaman iyi bir fikir değildir. Eğer 100 kullanıcı aynı anda web sitenize girerse ve siz Singleton ile <strong>tek bir veritabanı bağlantısı</strong> kullanıyorsanız, 99 kullanıcı ilk kullanıcının sorgusunun bitmesini beklemek zorunda kalır (kuyruk oluşur).</p><p><strong>Bağlantı Havuzu (Connection Pool)</strong> ise arka planda veritabanıyla örneğin 10 tane bağlantı açar ve bunları hazırda bekletir. Gelen kullanıcıya boşta olan bir bağlantıyı verir, işi bitince o bağlantıyı silmez, “havuza” geri koyar.</p><p>Python’da bunu sıfırdan yazmak yerine sektör standardı olan <strong>SQLAlchemy</strong> gibi kütüphaneler kullanılır.</p><p><strong>Kod Örneği (SQLAlchemy ile):</strong></p><pre>from sqlalchemy import create_engine<br># Veritabanı motorunu (engine) oluştururken bir havuz tanımlıyoruz.<br># pool_size=5: Havuzda sürekli açık tutulacak bağlantı sayısı (5 kişi aynı anda sorgu atabilir)<br># max_overflow=10: Yoğunlukta anlık olarak ekstra açılabilecek maksimum bağlantı sayısı<br>engine = create_engine(<br>    &#39;postgresql://kullanici:sifre@localhost:5432/benim_veritabanim&#39;, <br>    pool_size=5,<br>    max_overflow=10<br>)<br><br>def veritabanina_yaz(veri):<br>    # Kullanıcı geldiğinde havuzdan boşta olan bir bağlantı &quot;ödünç&quot; alınır<br>    with engine.connect() as connection:<br>        # İşlem yapılır...<br>        # connection.execute(&quot;INSERT INTO tablo ...&quot;)<br>        pass<br>    <br>    # &#39;with&#39; bloğu bittiğinde bağlantı KAPANMAZ! <br>    # Sadece diğer kullanıcıların alabilmesi için havuza (pool) iade edilir.</pre><p><strong>Nerede Kullanılır:</strong> FastAPI, Flask veya Django gibi web iskeletlerinde, aynı anda birden fazla kullanıcının veritabanına erişmesi gereken her türlü modern uygulamada standart yöntem budur.</p><h3>Özetle Hangisi Seçilmeli?</h3><ul><li>Amacınız uygulamadaki herkesin aynı dosyaya yazmasını (Log) veya aynı ayarları okumasını sağlamaksa: <strong>Thread-Safe Singleton</strong></li><li>Amacınız çok sayıda kullanıcının veritabanına hızlıca ve birbirini beklemeden erişmesini sağlamaksa: <strong>Connection Pool</strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4c46945f466" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Singleton]]></title>
            <link>https://emrecglar.medium.com/singleton-ef7795a79563?source=rss-9d515996c3ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef7795a79563</guid>
            <dc:creator><![CDATA[emrecglar]]></dc:creator>
            <pubDate>Sun, 12 Apr 2026 06:53:19 GMT</pubDate>
            <atom:updated>2026-04-12T06:53:19.970Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Singleton</strong>, bir sınıftan uygulama boyunca yalnızca <strong>bir tane nesne (instance)</strong> oluşturulmasını ve bu nesneye her yerden küresel (global) bir erişim sağlanmasını garanti eden bir tasarım desenidir.</p><p>Python’da bunu yapmanın birkaç yolu vardır ancak en yaygın olanı sınıfın __new__ metodunu ezmektir (override).</p><p>İşte adım adım kullanım şekilleri, gerçek hayat senaryoları ve performans etkileri:</p><h3>1. Python’da Temel Singleton Kullanımı</h3><p>Python’da bir nesne oluşturulurken önce __new__ metodu çalışır, sonra __init__ ile nesne başlatılır. Biz __new__ metoduna müdahale ederek, daha önce bir nesne oluşturulmuşsa yenisini yapmak yerine eskisini döndürebiliriz.</p><p>class Singleton:<br> _instance = None def __new__(cls, *args, **kwargs):<br> if cls._instance is None:<br> # Eğer daha önce nesne yaratılmadıysa, yarat ve kaydet<br> cls._instance = super(Singleton, cls).__new__(cls)<br> # Yaratılmışsa veya az önce yaratıldıysa aynı nesneyi döndür<br> return cls._instance# Test edelim<br>obje1 = Singleton()<br>obje2 = Singleton()<br>print(obje1 is obje2) # Çıktı: True (İkisi de bellekteki aynı nesnedir)</p><h3>2. Gerçek Hayat Kullanımları</h3><p>Veritabanı bağlantıları ve loglama işlemleri, Singleton deseninin en çok kullanıldığı yerlerdir çünkü bu işlemlerde tekrar tekrar bağlantı veya dosya açmak çok masraflıdır.</p><h4>A. Loglama (Logging) İşlemi</h4><p>Uygulamanın farklı dosyalarından log yazmak istediğinizde, aynı log dosyasını tekrar tekrar açıp kapatmak yerine tek bir Logger nesnesi kullanırsınız.</p><p>Python</p><pre>import loggingclass LoggerSingleton:<br>    _instance = None<br> def __new__(cls):<br>        if cls._instance is None:<br>            cls._instance = super(LoggerSingleton, cls).__new__(cls)<br>            <br>            # Loglama ayarlarını sadece ilk seferde yapıyoruz<br>            cls._instance.logger = logging.getLogger(&quot;AppLogger&quot;)<br>            cls._instance.logger.setLevel(logging.INFO)<br>            handler = logging.FileHandler(&quot;app_logs.log&quot;)<br>            formatter = logging.Formatter(&#39;%(asctime)s - %(message)s&#39;)<br>            handler.setFormatter(formatter)<br>            cls._instance.logger.addHandler(handler)<br>            <br>        return cls._instance<br><br># Kullanımı:<br>log1 = LoggerSingleton().logger<br>log2 = LoggerSingleton().logger<br>log1.info(&quot;Uygulama başladı.&quot;)<br>log2.info(&quot;Kullanıcı giriş yaptı.&quot;) <br># İkisi de aynı log nesnesini kullanarak aynı dosyaya yazar.</pre><h4>B. Veritabanı (Database) Bağlantısı</h4><p>Her sorguda veritabanına yeni bir bağlantı (TCP handshake, kimlik doğrulama vb.) kurmak çok yavaştır. Singleton ile bir kere bağlanır, hep o bağlantıyı kullanırsınız.</p><pre>import sqlite3<br>class DatabaseSingleton:<br>    _instance = None<br><br>def __new__(cls):<br>        if cls._instance is None:<br>            cls._instance = super(DatabaseSingleton, cls).__new__(cls)<br>            # Veritabanı bağlantısını sadece bir kere aç<br>            cls._instance.connection = sqlite3.connect(&quot;my_database.db&quot;)<br>            print(&quot;Veritabanına bağlanıldı!&quot;)<br>        return cls._instance<br># Kullanımı:<br>db1 = DatabaseSingleton()<br>db2 = DatabaseSingleton()<br># &quot;Veritabanına bağlanıldı!&quot; yazısı sadece 1 kere ekrana basılır.<br>cursor = db1.connection.cursor()<br>cursor.execute(&quot;SELECT sqlite_version();&quot;)<br>print(cursor.fetchone())</pre><h3>3. Hız ve Performans Farkı Ne Kadar Olur?</h3><p>Singleton kullanmanın hız farkı, arka planda engellediği <strong>işlemin maliyetine</strong> göre devasa boyutlarda olabilir.</p><ul><li><strong>Veritabanı Hızı:</strong> Normalde bir PostgreSQL veya MySQL veritabanına bağlanmak ortalama <strong>20–100 milisaniye</strong> sürer (Ağ gecikmesi, güvenlik doğrulaması vs.). Eğer 1000 kullanıcılık bir işlemde her seferinde yeni nesne üretip bağlanırsanız, sadece bağlantı kurmak <strong>20 ila 100 saniye</strong> sürer. Singleton ile bu süre <strong>0&#39;a iner</strong> (sadece ilk seferde 100 ms harcanır), çünkü bağlantı zaten açıktır ve hazırdır. Sadece sorgunun kendi süresini beklersiniz.</li><li><strong>Loglama Hızı:</strong> Diske erişim (I/O) işlemleri, bellekte (RAM) çalışmaya göre binlerce kat yavaştır. Her log mesajında dosyayı bulmak, açmak, yazmak ve kapatmak çok ciddi bir darboğaz (bottleneck) yaratır. Singleton bu dosya referansını bellekte tuttuğu için loglama süresi mikro saniyelere düşer.</li><li><strong>Bellek (RAM) Tasarrufu:</strong> 1000 tane ayrı nesne oluşturmak yerine bellekte (RAM) sadece 1 tane nesne tutulduğu için bellek tüketimi önemli ölçüde azalır.</li></ul><blockquote><strong><em>Önemli Gerçeklik Payı:</em></strong><em> Eğer çoklu iş parçacıklı (multithreading) bir uygulama yazıyorsanız, temel Singleton yapısı aynı anda iki thread’in </em><em>__new__ metoduna girmesiyle bozulabilir (Race Condition). Bu durumda &quot;Thread-Safe&quot; (İş parçacığı güvenli) bir Singleton yazmak gerekir. Ayrıca çok yoğun veritabanı işlemlerinde tek bir bağlantı (Singleton) yetersiz kalabilir, bu durumda Singleton yerine </em><strong><em>Connection Pool (Bağlantı Havuzu)</em></strong><em> kullanmak sektör standardıdır.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef7795a79563" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[thread]]></title>
            <link>https://emrecglar.medium.com/thread-a851d6e29e5b?source=rss-9d515996c3ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/a851d6e29e5b</guid>
            <dc:creator><![CDATA[emrecglar]]></dc:creator>
            <pubDate>Fri, 10 Apr 2026 18:46:28 GMT</pubDate>
            <atom:updated>2026-04-10T18:46:28.827Z</atom:updated>
            <content:encoded><![CDATA[<p>Çoğu insan daha fazla çekirdeğin (core) veya iş parçacığının (thread), işlemcinin saat hızını (GHz) sihirli bir şekilde artırdığını veya kod satırlarının daha hızlı çalışmasını sağladığını düşünür. Oysa durum senin de belirttiğin gibi tamamen <strong>donanımın potansiyelini maksimize etmek ve atıl (idle) zamanı sıfıra indirmekle</strong> ilgilidir.</p><p>Bu konuyu mimari ve donanım seviyesinde daha detaylı inceleyelim:</p><h3>1. “Hız” (Latency) ve “Kapasite” (Throughput) Yanılgısı</h3><p>Bir işlemcinin tek bir çekirdeği 4.0 GHz hızında çalışıyorsa, bir saniyede yapabileceği işlem döngüsü bellidir. Sen sisteme 100 tane thread de eklesen, o çekirdek içindeki fiziksel transistörlerin açılıp kapanma hızı (latency) değişmez.</p><ul><li><strong>Otoyol Analojisi:</strong> İşlemcinin saat hızını (GHz) yoldaki hız sınırı (120 km/s), çekirdek sayısını ise şerit sayısı olarak düşün. 4 şeritli bir yol yaptığında arabalar birdenbire 200 km/s hızla gitmeye başlamaz (hızlanmaz). Sadece aynı anda yola çıkabilen araba sayısı artar (kapasite/throughput). Hedefe varış süresi kısalır, çünkü arabalar tek şeritte trafik sıkışıklığı beklemez.</li></ul><h3>2. Threading: Bekleme Sürelerini Yok Etmek (Concurrency)</h3><p>Thread kullanımının temel amacı “aynı anda iki iş yapmak” değil, <strong>“bir iş beklerken diğerine devam etmektir”</strong> (Eşzamanlılık — Concurrency).</p><p>Örneğin bir ağ taraması (network scanning) veya web scraping aracı yazdığını düşün. Kodun bir sunucuya istek attığında, karşıdan cevap gelene kadar geçen sürede CPU aslında hiçbir şey yapmaz, sadece bekler (I/O Bound işlem).</p><p>Eğer thread kullanırsan, işletim sisteminin zamanlayıcısı (scheduler) devreye girer: <em>“A thread’i ağdan cevap bekliyor, o sırada işlemci boş durmasın, B thread’ini çalıştırayım.”</em> der. İşlemci hızlanmamıştır, sadece boş vaktini değerlendirerek donanımı <strong>maksimum efektiflikte</strong> kullanmıştır.</p><h3>3. Çoklu Çekirdek (Multicore): Gerçek Paralellik (Parallelism)</h3><p>Multicore sistemler, işi donanımsal olarak bölebildiğin durumlarda (CPU Bound işlemler) parlar. Örneğin bir parola özetini (hash) kırmak (brute-force) veya büyük bir veri setini şifrelemek istiyorsun.</p><p>Tek çekirdek saniyede 1 milyon hash deneyebilir. 8 çekirdekli bir sistemde işi 8&#39;e böldüğünde, her çekirdek yine saniyede 1 milyon hash dener (işlem hızlanmamıştır). Ancak toplam sistem saniyede 8 milyon hash denediği için işin <strong>bitiş süresi</strong> kısalır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*Y3l96UvAApe6VQh1ktj85A.png" /></figure><p>Eğer yazdığın kodun %50&#39;si ardışık (sequential — adım adım çalışmak zorunda olan) bir mantığa sahipse, sonsuz tane çekirdeğin ($N \to \infty$) olsa bile sistemin toplam performansı en fazla 2 kat artabilir. Çünkü kodun yarısı tek bir çekirdekte sırayla işlenmeyi beklemek zorundadır.</p><h3>5. Python’daki Özel Durum: GIL (Global Interpreter Lock)</h3><p>Konu donanımı efektif kullanmak olduğunda, kullanılan dilin mimarisi de çok önemlidir. Örneğin Python’da CPython referans uygulamasından kaynaklanan <strong>GIL (Global Interpreter Lock)</strong> bulunur.</p><p>GIL, aynı anda sadece tek bir thread’in Python bytecode’unu çalıştırmasına izin verir. Yani Python’da CPU’yu yoran ağır bir matematiksel işlem için 10 tane thread de açsan, bu thread’ler çoklu çekirdeklerine dağılıp aynı anda çalışamazlar. Sırayla çalışırlar. Bu yüzden Python’da donanımı gerçekten efektif kullanmak (multicore avantajı sağlamak) için threading kütüphanesi yerine, işletim sistemi seviyesinde tamamen ayrı bellek alanları yaratan multiprocessing kütüphanesi kullanılır.</p><p>Özetle; sistem mimarisine, yazdığın koda ve işletim sisteminin kernel’ına ne kadar hakim olursan, elindeki donanımın her bir transistörünü o kadar “terletir” ve atıl kapasiteyi o kadar azaltırsın. Hız, bu verimliliğin sadece doğal bir yan etkisidir.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a851d6e29e5b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Asp.net web api Arama(Searching)]]></title>
            <link>https://emrecglar.medium.com/asp-net-web-api-arama-searching-3a902866407c?source=rss-9d515996c3ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a902866407c</guid>
            <dc:creator><![CDATA[emrecglar]]></dc:creator>
            <pubDate>Sat, 18 Oct 2025 15:23:37 GMT</pubDate>
            <atom:updated>2025-10-18T15:23:37.872Z</atom:updated>
            <content:encoded><![CDATA[<p>Hemen hemen bütün apilerin ihtiyaç duyabileceği bir yapı. Searching terim ya da anahtar değer yardımıyla uygulama içerisindeki en alakalı sonuçları döndürmek üzere uygulanan bir işlevdir. /books?searchTerm=kara,/books?searchTerm=Kara,/books?searchTerm=KARA,/books?searchTerm=kArA gibi gelebilir küçük büyük duyarlığını ele alarak bir arama işlemi yapacağız. Lucene.net kullanabiliriz kütüphane seçiminde.</p><h4>Arama implementasyonu:</h4><p>Varlık katmanında bir parametre tanımı yapacağız.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*Q3b4cKsjMZo8o4-lpn7ySQ.png" /><figcaption>RequestParameters üzerinde de yapabilirdik.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*UtpjqaNqkeCJ4xNW876ieA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XOc8275nsqMfToFmobXjlA.png" /></figure><p>Searching, Web API’lerde kullanıcıların bir anahtar kelime (searchTerm) ile veritabanındaki ilgili kayıtları bulmasını sağlayan, case-insensitive (büyük/küçük harf duyarsız) çalışan temel bir filtreleme mekanizmasıdır.</p><p>Temel Kavram: Kullanıcı /books?searchTerm=kara, /books?searchTerm=Kara, /books?searchTerm=KARA veya /books?searchTerm=kArA şeklinde istek gönderdiğinde, sistemin tüm bu varyasyonları aynı şekilde algılayıp &quot;Karamazov Kardeşler&quot;, &quot;Kara Kitap&quot;, &quot;Karanfil&quot; gibi ilgili tüm sonuçları döndürmesi gerekir. Bu, kullanıcı deneyimini önemli ölçüde iyileştirir çünkü kullanıcı büyük/küçük harf konusunda endişelenmeden arama yapabilir.</p><p>İmplementasyon Seçenekleri:</p><p>1. Basit String Karşılaştırma (Küçük Uygulamalar için):</p><pre>public static IQueryable&lt;Book&gt; Search(this IQueryable&lt;Book&gt; books, string searchTerm)<br>{<br>    if (string.IsNullOrWhiteSpace(searchTerm))<br>        return books;<br>    <br>    var lowerSearchTerm = searchTerm.Trim().ToLower();<br>    <br>    return books.Where(b =&gt; <br>        b.Title.ToLower().Contains(lowerSearchTerm) || <br>        b.Author.ToLower().Contains(lowerSearchTerm) ||<br>        b.Description.ToLower().Contains(lowerSearchTerm));<br>}</pre><p>Bu yaklaşım basit ama performans sorunları yaratabilir çünkü ToLower() index kullanımını engelleyebilir.</p><p>2. EF Core ile Database-Level Arama:</p><pre>public static IQueryable&lt;Book&gt; Search(this IQueryable&lt;Book&gt; books, string searchTerm)<br>{<br>    if (string.IsNullOrWhiteSpace(searchTerm))<br>        return books;<br>    <br>    var searchPattern = $&quot;%{searchTerm}%&quot;;<br>    <br>    return books.Where(b =&gt; <br>        EF.Functions.Like(b.Title, searchPattern) || <br>        EF.Functions.Like(b.Author, searchPattern) ||<br>        EF.Functions.Like(b.Description, searchPattern));<br>}</pre><p>EF.Functions.Like() veritabanı seviyesinde case-insensitive karşılaştırma yapar ve SQL Server&#39;da collation ayarlarını kullanır.</p><p>3. Lucene.NET ile Full-Text Search (Büyük ve Karmaşık Uygulamalar için): Lucene.NET, Apache Lucene’in .NET implementasyonu olup enterprise-level full-text search sağlar. Özellikleri:</p><ul><li>Fuzzy search: Yazım hatalarını tolere eder (“karamazov” yerine “karamzov” yazılsa bile bulur)</li><li>Relevance scoring: Sonuçları alakalılığa göre sıralar</li><li>Tokenization: Metinleri kelimelere ayırır ve analiz eder</li><li>Performance: Milyonlarca kayıt arasında milisaniyeler içinde arama yapar</li><li>Advanced queries: Boolean operatörler, wildcard, phrase search destekler</li></ul><pre>// Lucene.NET index oluşturma<br>var indexPath = &quot;lucene_index&quot;;<br>var analyzer = new StandardAnalyzer(LuceneVersion.LUCENE_48);<br>var indexConfig = new IndexWriterConfig(LuceneVersion.LUCENE_48, analyzer);<br>var writer = new IndexWriter(FSDirectory.Open(indexPath), indexConfig);<br>// Kitap indexleme<br>foreach (var book in books)<br>{<br>    var doc = new Document();<br>    doc.Add(new StringField(&quot;Id&quot;, book.Id.ToString(), Field.Store.YES));<br>    doc.Add(new TextField(&quot;Title&quot;, book.Title, Field.Store.YES));<br>    doc.Add(new TextField(&quot;Author&quot;, book.Author, Field.Store.YES));<br>    writer.AddDocument(doc);<br>}<br>writer.Commit();<br>// Arama yapma<br>var searcher = new IndexSearcher(reader);<br>var queryParser = new MultiFieldQueryParser(LuceneVersion.LUCENE_48, <br>    new[] { &quot;Title&quot;, &quot;Author&quot; }, analyzer);<br>var query = queryParser.Parse(searchTerm.ToLower());<br>var hits = searcher.Search(query, 100);</pre><p>Hangi Yaklaşımı Seçmeli:</p><ul><li>10.000&#39;den az kayıt, basit arama: EF.Functions.Like() yeterli</li><li>100.000+ kayıt, karmaşık sorgular, fuzzy search gereksinimi: Lucene.NET veya ElasticSearch</li><li>Cloud-based, ölçeklenebilir: Azure Cognitive Search veya AWS OpenSearch</li></ul><p>Best Practices:</p><ul><li>Arama terimini mutlaka Trim() ile temizleyin</li><li>Boş veya null searchTerm için filtreleme yapmadan tüm sonuçları döndürün</li><li>Çok kısa terimleri (1–2 karakter) kabul etmeme düşünülebilir (performans için)</li><li>Lucene.NET kullanıyorsanız index’i düzenli güncelleyin</li><li>Arama sonuçlarını sayfalama ile birlikte kullanın</li><li>İlgili field’lara database index ekleyin</li></ul><p>Bu sistem sayesinde kullanıcılar ne şekilde yazarlarsa yazsınlar istedikleri sonuçlara ulaşabilir ve modern bir API deneyimi sunar.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a902866407c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Asp.net AutoMapper]]></title>
            <link>https://emrecglar.medium.com/asp-net-automapper-069e6994e113?source=rss-9d515996c3ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/069e6994e113</guid>
            <dc:creator><![CDATA[emrecglar]]></dc:creator>
            <pubDate>Sat, 18 Oct 2025 14:41:33 GMT</pubDate>
            <atom:updated>2025-10-18T14:41:33.645Z</atom:updated>
            <content:encoded><![CDATA[<p>Sunucu ile istemci arasında verileri yer değiştirdiğimizde işimize yarayacak bir kütüphanedir.</p><p>Öncelikle http nasıl çalışır: istemci bir request atıyor bazı veriler içerisinde bazı veriler sıkıştırılmış olabilir mesela kullanıcını id’si gönderilir ama tüm verileri gönderilmez. Genelde de kullanıcının id’si gönderilir sadece rol vsde yollanmaz kod üzerinde sorgulama yapılır. request bir endpoint’e geldiği zaman bu noktada mapper kullanıldığı zaman mapper kullanmak çok işimize yarar responseye dönüştürmeye aşamasında. Rest stateless olarak çalışır.</p><p><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status">https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status</a> tüm http status kodları.</p><h3>Automapping:</h3><p>Elimizde bir kaynak(Source) ve hedef(Destination) olsun. DTO ile iletişim sağlarız. DTO ile gerçek sınıfı maplemeyi AutoMapping ile mapleyeceğiz. DTO’dan gerçek class’a gerçek class’tan DTO’ya işlem yapabiliriz. tersi de geçerli yani. ASP.NET için automapping terimi, genellikle <strong>object-to-object mapping</strong> (nesne-nesne eşleme) sürecini otomatikleştiren bir konsepti ifade eder ve en yaygın kullanımı <strong>AutoMapper</strong> kütüphanesiyle gerçekleştirilir. ASP.NET uygulamalarında farklı katmanlar arasında veri aktarımı sırasında (örneğin veritabanı entity’lerini DTO’lara, ViewModel’leri domain model’lere dönüştürme gibi) sürekli olarak bir nesnenin özelliklerini başka bir nesneye manuel olarak kopyalamak gerekir ki bu hem tekrarlayan kod yazmaya hem de hatalara açık bir sürece yol açar. AutoMapper gibi kütüphaneler, kaynak ve hedef tipler arasında konvansiyona dayalı (aynı isimli property’ler otomatik eşleşir) veya özel konfigürasyonlarla tanımlanmış mapping profilleri oluşturarak bu süreci otomatikleştirir. Örneğin, bir User entity&#39;sini UserDto&#39;ya dönüştürmek istediğinizde, mapper.Map&lt;UserDto&gt;(user) gibi tek bir satırla tüm uygun property&#39;ler otomatik olarak kopyalanır. Bu yaklaşım, özellikle Clean Architecture veya katmanlı mimarilerde katmanlar arası veri transferinde kod tekrarını önler, maintainability&#39;yi (bakım yapılabilirliği) artırır ve boilerplate kodları minimize eder. AutoMapper, ASP.NET Core&#39;da dependency injection ile entegre edilebilir, karmaşık nested object mapping&#39;leri destekler, custom resolver&#39;lar ve value converter&#39;larla özelleştirilebilir, ayrıca performans optimizasyonu için runtime&#39;da compile edilen expression tree&#39;ler kullanır.</p><h3>Paket kurulumu ve yapılandırma:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*_Wt39IekCEvHDG-sPckC2g.png" /><figcaption>bu komut ile kurulumu yaparız ama mimariye göre bu değişir. CleanArchitecturede bizim Domain/Core katmamında kullanmamız gerekir. Application katmanı gayet uygundur. Özetle: Infrastructure katmanında <strong>persistence ↔ domain</strong> mapping’i, Application katmanında <strong>domain ↔ DTO/response</strong> mapping’i, Presentation katmanında ise <strong>request DTO ↔ command/query</strong> mapping’i yapılır. AutoMapper profilleri genellikle ilgili katmanın içinde (örneğin Infrastructure/Mappings veya Application/Mappings klasörlerinde) tanımlanır ve her katman sadece kendi sorumluluğundaki dönüşümleri gerçekleştirir, böylece Dependency Inversion prensibi korunmuş olur.</figcaption></figure><p>Şimdi konfigure edeceğiz. builder.Services.AddAutoMapper(typeof(Program)); [web api her şeyin derlenip toplandığı ve yayına çıktığı yapıdır. bu yüzden onun referansını kullanırız.]</p><h4>record type:</h4><p><strong>Record type</strong>, C# 9.0 ile tanıtılan ve <strong>immutable (değiştirilemez) veri taşımak için optimize edilmiş</strong> özel bir reference type’dır (C# 10&#39;dan itibaren record struct ile value type olarak da kullanılabilir).</p><p>Record’lar, öncelikle <strong>veri odaklı nesneler</strong> (data-centric objects) için tasarlanmıştır ve DTO’lar, Value Object’ler, API response/request modelleri gibi sadece veri taşıyan, davranış içermeyen yapılar için idealdir. Normal class’lardan temel farkları, derleyicinin otomatik olarak birçok yararlı özellik eklemesidir:</p><p><strong>Record’ların Otomatik Sağladığı Özellikler:</strong></p><ol><li><strong>Value-based equality:</strong> İki record, referansları değil, içerdikleri değerlere göre karşılaştırılır. Equals(), GetHashCode(), == ve != operatörleri otomatik implement edilir.</li><li><strong>Immutability:</strong> Primary constructor’da tanımlanan property’ler varsayılan olarak init-only&#39;dir (sadece oluşturma sırasında atanabilir).</li><li><strong>With-expressions:</strong> Mevcut record’dan bazı property’leri değiştirerek yeni bir kopya oluşturabilirsiniz: var newDto = oldDto with { id = 5 };</li><li><strong>Deconstruction:</strong> var (id, ad) = dto; şeklinde property&#39;leri ayrıştırabilirsiniz.</li><li><strong>ToString override:</strong> Otomatik olarak anlamlı bir string representation üretir: &quot;DTO { id = 1, ad = Test }&quot;</li></ol><p><strong>Kullanım Örnekleri:</strong></p><pre>// Basit record<br>public record Person(string Name, int Age);<br>// Ekstra property&#39;lerle<br>public record User(int Id, string Email)<br>{<br>    public DateTime CreatedAt { get; init; } = DateTime.UtcNow;<br>}<br>// Mutable record (istenirse)<br>public record Product(int Id)<br>{<br>    public string Name { get; set; }<br>}<br>// Record struct (value type)<br>public record struct Point(int X, int Y);</pre><p><strong>Ne Zaman Kullanılır:</strong> DTO’lar, configuration nesneleri, domain events, value objects, query/command nesneleri gibi immutable veri yapılarında. <strong>Ne Zaman Kullanılmaz:</strong> Entity’ler (identity-based equality gerektiren), karmaşık davranışlara sahip domain modelleri, mutable state gerektiren nesnelerde class tercih edilmelidir.</p><h3>DTO:</h3><p>mapleme yapmak istediğimiz zaman kullanmamız gereken bir yapıdır. Data transfer object olarak geçer. [Clean Archta Application katmanında tanımlanırlar genel olarak. Presentation katmanında ise sadece API’ye özgü request/response model’lerini tutmak ve aralarında ince bir mapping layer kullanmaktır. Ama Genelde Application katmanında] DTOları request ve response klasörlerine bölerek kullanabiliriz. Daha mantıklı olacaktır.</p><h4>DTO readonly(immutable) olmalıdır, Değişmemelidir. LINQ desteği olmalıdır. Ref type olmalıdır class ile aynı özellikleri taşımalı. Ctor tanımlama şansı vermelidir.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/237/1*MKwQapEjwkMEghdT6zeBTw.png" /><figcaption>Mesela buradaki init ile readonly immutable olma sistemini kurabiliriz.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*cebIx6rxzEgZVPn9GO1JSw.png" /><figcaption>DTO’yu bu şekilde tanımlayabiliriz. Veya alttaki resimdeki gibi tanımlayabiliriz.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*8LoSBYyHXZXJ8hZF2Pl5VQ.png" /><figcaption>Ya da bu şekilde tanımlama yapabiliriz. Bu şekilde de readonly olur otomatik olarak ve ek olarak back tick eklenir nesne serialize olduğu zaman kullanabileceğimiz bir şeydirk__BackingField yapısı, C# dilinde <strong>auto-implemented property&#39;ler</strong> (otomatik özellikler) için derleyici tarafından otomatik olarak oluşturulan <strong>gizli backing field&#39;ın</strong> (destek alanının) adıdır.. Bu tür şeyleri sharplab.io kullanarak görebiliriz. C#’ın derleyisinin ne sonuç verdiğini gösterir.</figcaption></figure><p><a href="https://sharplab.io/">SharpLab</a></p><h4>Profil oluşturma:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*_wJrxmXFo5lrpztww-o_kA.png" /><figcaption>Bu yapı ile profil oluşturduk.</figcaption></figure><h3>AutoMapper kullanımı:</h3><p>private readonly IMapper _mapper; sonrasında ise Ctor içerisinde DI yaparız.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*sB-vLViOzjYPLKY4WF5s2w.png" /><figcaption>Bu şekilde ekledik.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*j57drf-orIt7qzsKjT3qKw.png" /><figcaption>Bu şekilde mapleme yapabilir olduk.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*iavZgAGcivBvf1vDC8hQtw.png" /><figcaption>Doğrudan injection burada gerçeklemiş oluyor böylece.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=069e6994e113" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[asp.net web api hız sınırlama]]></title>
            <link>https://emrecglar.medium.com/asp-net-web-api-h%C4%B1z-s%C4%B1n%C4%B1rlama-ad733d806431?source=rss-9d515996c3ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad733d806431</guid>
            <dc:creator><![CDATA[emrecglar]]></dc:creator>
            <pubDate>Sat, 18 Oct 2025 11:23:11 GMT</pubDate>
            <atom:updated>2025-10-18T11:23:11.358Z</atom:updated>
            <content:encoded><![CDATA[<p>Hız sınırlama her api’nin ihtiyaç duyabileceği bir sistemdir.</p><p>AspNetCoreRateLimit kütüphanesi kullanacağız</p><p>Bir konfigurasyon yapacağız.</p><p>X-Rate-Limit-Limit</p><p>X-Rate-Limit-Remaining</p><p>X-Rate-Limit-Reset</p><p>429 Too Many requests.(Belirlenen limitin dışına çıkılırsa)</p><h3>AspNetCoreRateLimit kütüphanesini kuracağız. Bunu Program.cs’in olduğu yere kuracağız (web api projesi) böylece middleware yapısı gibi kullanılacak bu sistem.</h3><h3>Şimdi yapılandırma:</h3><p>builder.Services.AddMemoryCache(); ifadesini builder’a eklememiz gerekiyor çünkü Cache kullanacağız.</p><p>Extensions klasöründe web api içerisinde ServicesExtensions dosyasında metot ekleyeceğiz bu metot içerisinde çok sayıda konfigürasyon yapabiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*05CS7sKBASc0rnpc-3LoHQ.png" /><figcaption>IOC kaydı Singleton defaya mahsus oluşacak bir kere oluşması yeterli. IRateLimitCounterStore’u MemoryCacheRateLimitCounterStore üzerinden çözeceğiz. diğerleri de aynı biçimde. İkinci girilen ilk girileni çözmeye yarar.</figcaption></figure><p>Bu metottan sonra builder.Services.ConfigureRateLimitingOptions(); ile kayıt ederiz metotumuzu. Sonra bir tane daha servis kaydı yaparız. builder.Services.AddHttpContextAccessor();</p><p>Cors yapılandırmasının üstünde bir yerde app.UseIpRateLimiting() kullanacağız</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/1*KNzpmrYvknLkOXFaRg5Alw.png" /></figure><p>Api testi ile X-Rate-Limit-Limit, X-Rate-Limit-Remaining,X-Rate-Limit-Reset başlıklarını görebiliriz headers üzerinde.</p><p>Bu sistem oldukça kullanışlı ve genişletilip özelleştirilebilir bir sistem. Kesinlikle kullanmak gerekiyor diye düşünüyorum fazla istek ile yapılacak kötü amaçlı saldırılara karşı bizi iyice koruyabilir.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad733d806431" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JSON (JavaScript Object Notation)]]></title>
            <link>https://emrecglar.medium.com/json-javascript-object-notation-9ea0f1003887?source=rss-9d515996c3ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ea0f1003887</guid>
            <dc:creator><![CDATA[emrecglar]]></dc:creator>
            <pubDate>Fri, 12 Sep 2025 21:14:37 GMT</pubDate>
            <atom:updated>2025-09-12T21:14:37.511Z</atom:updated>
            <content:encoded><![CDATA[<h3>JSON Nedir?</h3><p>JSON, veri alışverişi için kullanılan hafif, metin tabanlı bir veri formatıdır. İsmi JavaScript Object Notation olmasına rağmen, programlama dilinden bağımsızdır ve neredeyse tüm modern programlama dilleri tarafından desteklenir.</p><h3>JSON’un Temel Özellikleri</h3><p><strong>Avantajları:</strong></p><ul><li>İnsan tarafından okunabilir</li><li>Makineler tarafından kolayca işlenebilir</li><li>XML’e göre daha hafif ve hızlı</li><li>Web API’larında standart format</li><li>Programlama dillerinin çoğunda yerli destek</li></ul><p><strong>Dezavantajları:</strong></p><ul><li>Yorum (comment) desteklenmez</li><li>Tarih formatı standardı yok</li><li>Fonksiyon veya undefined değerleri desteklenmez</li><li>Binary veri doğrudan desteklenmez</li></ul><h3>JSON Veri Tipleri</h3><p>JSON altı temel veri tipini destekler:</p><h3>1. String (Metin)</h3><pre>{<br>  &quot;name&quot;: &quot;Ahmet&quot;,<br>  &quot;city&quot;: &quot;İstanbul&quot;<br>}</pre><h3>2. Number (Sayı)</h3><pre>{<br>  &quot;age&quot;: 25,<br>  &quot;price&quot;: 99.99,<br>  &quot;temperature&quot;: -5.2<br>}</pre><h3>3. Boolean (Doğru/Yanlış)</h3><pre>{<br>  &quot;isActive&quot;: true,<br>  &quot;isCompleted&quot;: false<br>}</pre><h3>4. null (Boş)</h3><pre>{<br>  &quot;middleName&quot;: null<br>}</pre><h3>5. Object (Nesne)</h3><pre>{<br>  &quot;address&quot;: {<br>    &quot;street&quot;: &quot;Atatürk Caddesi&quot;,<br>    &quot;number&quot;: 123,<br>    &quot;district&quot;: &quot;Kadıköy&quot;<br>  }<br>}</pre><h3>6. Array (Dizi)</h3><pre>{<br>  &quot;colors&quot;: [&quot;red&quot;, &quot;green&quot;, &quot;blue&quot;],<br>  &quot;numbers&quot;: [1, 2, 3, 4, 5],<br>  &quot;mixed&quot;: [&quot;text&quot;, 123, true, null]<br>}</pre><h3>JSON Söz Dizimi Kuralları</h3><ol><li><strong>Çift tırnak kullanımı</strong>: Tüm string değerler ve anahtar isimler çift tırnak içinde olmalı</li><li><strong>Virgül kullanımı</strong>: Son öğeden sonra virgül kullanılmaz</li><li><strong>Süslü parantez</strong>: Objeleri sarmallar {}</li><li><strong>Köşeli parantez</strong>: Dizileri sarmallar []</li><li><strong>İki nokta üst üste</strong>: Anahtar-değer çiftlerini ayırır</li><li><strong>Virgül</strong>: Öğeleri ayırır</li></ol><h3>Karmaşık JSON Örneği</h3><p>json</p><pre>{<br>  &quot;company&quot;: {<br>    &quot;name&quot;: &quot;TechCorp&quot;,<br>    &quot;founded&quot;: 2015,<br>    &quot;headquarters&quot;: {<br>      &quot;country&quot;: &quot;Turkey&quot;,<br>      &quot;city&quot;: &quot;Istanbul&quot;,<br>      &quot;address&quot;: {<br>        &quot;street&quot;: &quot;Teknoloji Caddesi&quot;,<br>        &quot;number&quot;: 42,<br>        &quot;postalCode&quot;: &quot;34000&quot;<br>      }<br>    },<br>    &quot;employees&quot;: [<br>      {<br>        &quot;id&quot;: 1,<br>        &quot;name&quot;: &quot;Ali Yılmaz&quot;,<br>        &quot;position&quot;: &quot;Software Engineer&quot;,<br>        &quot;salary&quot;: 75000,<br>        &quot;skills&quot;: [&quot;JavaScript&quot;, &quot;Python&quot;, &quot;React&quot;],<br>        &quot;isActive&quot;: true,<br>        &quot;startDate&quot;: &quot;2020-03-15&quot;,<br>        &quot;contact&quot;: {<br>          &quot;email&quot;: &quot;ali@techcorp.com&quot;,<br>          &quot;phone&quot;: &quot;+90 555 123 4567&quot;<br>        }<br>      },<br>      {<br>        &quot;id&quot;: 2,<br>        &quot;name&quot;: &quot;Ayşe Demir&quot;,<br>        &quot;position&quot;: &quot;UX Designer&quot;,<br>        &quot;salary&quot;: 65000,<br>        &quot;skills&quot;: [&quot;Figma&quot;, &quot;Adobe XD&quot;, &quot;Sketch&quot;],<br>        &quot;isActive&quot;: true,<br>        &quot;startDate&quot;: &quot;2021-07-01&quot;,<br>        &quot;contact&quot;: {<br>          &quot;email&quot;: &quot;ayse@techcorp.com&quot;,<br>          &quot;phone&quot;: &quot;+90 555 987 6543&quot;<br>        }<br>      }<br>    ],<br>    &quot;departments&quot;: [&quot;Engineering&quot;, &quot;Design&quot;, &quot;Marketing&quot;, &quot;HR&quot;],<br>    &quot;technologies&quot;: {<br>      &quot;frontend&quot;: [&quot;React&quot;, &quot;Vue.js&quot;, &quot;Angular&quot;],<br>      &quot;backend&quot;: [&quot;Node.js&quot;, &quot;Python&quot;, &quot;Java&quot;],<br>      &quot;database&quot;: [&quot;PostgreSQL&quot;, &quot;MongoDB&quot;, &quot;Redis&quot;]<br>    },<br>    &quot;financials&quot;: {<br>      &quot;revenue&quot;: 2500000,<br>      &quot;expenses&quot;: 1800000,<br>      &quot;profit&quot;: 700000,<br>      &quot;currency&quot;: &quot;TRY&quot;<br>    },<br>    &quot;isPublic&quot;: false,<br>    &quot;website&quot;: &quot;https://techcorp.com&quot;<br>  }<br>}</pre><h3>Programlama Dillerinde JSON Kullanımı</h3><h3>JavaScript</h3><pre>// JSON string&#39;i objeye çevirme<br>const jsonString = &#39;{&quot;name&quot;: &quot;Ahmet&quot;, &quot;age&quot;: 30}&#39;;<br>const obj = JSON.parse(jsonString);<br>// Objeyi JSON string&#39;ine çevirme<br>const person = {name: &quot;Mehmet&quot;, age: 25};<br>const json = JSON.stringify(person);</pre><h3>Python</h3><pre>import json<br># JSON string&#39;i dictionary&#39;ye çevirme<br>json_string = &#39;{&quot;name&quot;: &quot;Ahmet&quot;, &quot;age&quot;: 30}&#39;<br>obj = json.loads(json_string)<br># Dictionary&#39;yi JSON string&#39;ine çevirme<br>person = {&quot;name&quot;: &quot;Mehmet&quot;, &quot;age&quot;: 25}<br>json_string = json.dumps(person)</pre><h3>Java</h3><pre>// Gson kütüphanesi ile<br>Gson gson = new Gson();<br>String json = gson.toJson(object);<br>Object obj = gson.fromJson(json, Object.class);</pre><h3>JSON Doğrulama ve Hata Tipleri</h3><p><strong>Yaygın JSON Hataları:</strong></p><ul><li>Eksik çift tırnak</li><li>Son öğeden sonra virgül</li><li>Yanlış parantez eşleştirmesi</li><li>Geçersiz karakter kullanımı</li><li>Tanımlanmamış değerler (undefined)</li></ul><p><strong>Doğru Format:</strong></p><pre>{<br>  &quot;name&quot;: &quot;valid&quot;,<br>  &quot;items&quot;: [1, 2, 3]<br>}</pre><p><strong>Yanlış Format:</strong></p><pre>{<br>  name: &quot;invalid&quot;,        // Tırnak yok<br>  &quot;items&quot;: [1, 2, 3,]     // Son virgül<br>}</pre><h3>JSON Schema</h3><p>JSON Schema, JSON verilerinin yapısını tanımlamak için kullanılır:</p><pre>{<br>  &quot;$schema&quot;: &quot;http://json-schema.org/draft-07/schema#&quot;,<br>  &quot;type&quot;: &quot;object&quot;,<br>  &quot;properties&quot;: {<br>    &quot;name&quot;: {<br>      &quot;type&quot;: &quot;string&quot;,<br>      &quot;minLength&quot;: 1<br>    },<br>    &quot;age&quot;: {<br>      &quot;type&quot;: &quot;integer&quot;,<br>      &quot;minimum&quot;: 0,<br>      &quot;maximum&quot;: 150<br>    }<br>  },<br>  &quot;required&quot;: [&quot;name&quot;, &quot;age&quot;]<br>}</pre><h3>Performans ve Optimizasyon</h3><p><strong>İyi Uygulamalar:</strong></p><ul><li>Gereksiz iç içe geçmişlikten kaçınma</li><li>Büyük dizilerde sayfalama kullanma</li><li>Gzip sıkıştırması uygulama</li><li>Önbellek stratejileri kullanma</li><li>Streaming JSON parser’ları kullanma (büyük dosyalar için)</li></ul><h3>Güvenlik Konuları</h3><p><strong>JSON Güvenlik Riskleri:</strong></p><ul><li>JSON Injection saldırıları</li><li>Büyük JSON dosyalarıyla DoS saldırıları</li><li>Hassas bilgilerin JSON içinde açıkta kalması</li></ul><p><strong>Güvenlik Önlemleri:</strong></p><ul><li>Input doğrulaması yapma</li><li>JSON boyut limitleri koyma</li><li>Hassas verileri şifreleme</li><li>CORS politikalarını doğru ayarlama</li></ul><h3>Alternatif Formatlar</h3><p><strong>XML ile karşılaştırma:</strong></p><ul><li>JSON daha hafif ve hızlı</li><li>XML daha zengin metadata desteği</li><li>JSON web API’larında tercih edilir</li></ul><p><strong>YAML ile karşılaştırma:</strong></p><ul><li>YAML daha okunabilir</li><li>JSON daha hızlı işlenir</li><li>YAML yorumlara izin verir</li></ul><h3>JSON Boyut ve Depolama Detaylı Analizi</h3><h3>📏 Temel Boyut Bilgileri</h3><p><strong>JSON’un Boyutunu Etkileyen Faktörler:</strong></p><ul><li><strong>Veri tipi</strong>: String veriler daha fazla yer kaplar</li><li><strong>Anahtar isimleri</strong>: Uzun anahtar isimleri boyutu artırır</li><li><strong>Formatlanma</strong>: Pretty-print (girintili) %20–30 daha fazla yer kaplar</li><li><strong>Tekrarlı veriler</strong>: Denormalize edilmiş veriler daha büyük</li><li><strong>Null değerler</strong>: Gereksiz null’lar alan israfı yapar</li></ul><h3>🗜️ Sıkıştırma Oranları</h3><p><strong>Gzip Sıkıştırması:</strong></p><ul><li>JSON dosyaları genellikle %70–80 sıkıştırılabilir</li><li>Tekrarlı veriler daha iyi sıkıştırılır</li><li>Minified JSON + Gzip = optimal boyut</li></ul><p><strong>Brotli Sıkıştırması:</strong></p><ul><li>Gzip’ten %15–20 daha iyi performans</li><li>Modern tarayıcıların çoğunda desteklenir</li></ul><h3>📊 Gerçek Dünya Örnekleri</h3><p><strong>1. Küçük JSON (Kullanıcı Profili):</strong></p><pre>Orijinal: 2.5 KB<br>Minified: 1.8 KB (-28%)<br>Gzipped: 0.7 KB (-72%)</pre><p><strong>2. Orta Boyut JSON (100 Ürün Listesi):</strong></p><pre>Orijinal: 450 KB<br>Minified: 380 KB (-16%)<br>Gzipped: 95 KB (-79%)</pre><p><strong>3. Büyük JSON (10,000 Kayıt):</strong></p><pre>Orijinal: 25 MB<br>Minified: 22 MB (-12%)<br>Gzipped: 6.5 MB (-74%)</pre><h3>⚡ Performans Etkileri</h3><p><strong>Parse Hızları (1MB JSON için):</strong></p><ul><li><strong>Chrome V8</strong>: ~15–25ms</li><li><strong>Firefox SpiderMonkey</strong>: ~20–35ms</li><li><strong>Safari JavaScriptCore</strong>: ~18–30ms</li><li><strong>Node.js</strong>: ~10–20ms</li></ul><p><strong>Bellek Kullanımı:</strong></p><ul><li>Parse edilmiş JSON belleğe 3–5x daha fazla yer kaplar</li><li>String veriler UTF-16 formatında saklanır (2 byte/karakter)</li></ul><h3>💾 Depolama Stratejileri</h3><p><strong>Veritabanında JSON Saklama:</strong></p><ul><li><strong>PostgreSQL</strong>: JSONB formatı binary olarak saklar, daha hızlı</li><li><strong>MongoDB</strong>: BSON formatı, ek tip bilgileri içerir</li><li><strong>MySQL</strong>: JSON sütunu native destek sunar</li></ul><p><strong>Dosya Sistemi:</strong></p><ul><li><strong>SSD</strong>: Random access için ideal</li><li><strong>HDD</strong>: Sequential read/write daha etkili</li><li><strong>Network Storage</strong>: Caching stratejisi kritik</li></ul><h3>🔧 Optimizasyon Teknikleri</h3><p><strong>1. Veri Normalizasyonu:</strong></p><p>json</p><pre>// Kötü - Tekrarlı veri (2.8 KB)<br>{<br>  &quot;users&quot;: [<br>    {&quot;name&quot;: &quot;Ali&quot;, &quot;city&quot;: &quot;İstanbul&quot;, &quot;country&quot;: &quot;Türkiye&quot;},<br>    {&quot;name&quot;: &quot;Veli&quot;, &quot;city&quot;: &quot;İstanbul&quot;, &quot;country&quot;: &quot;Türkiye&quot;}<br>  ]<br>}<br><br>// İyi - Normalize edilmiş (1.9 KB)<br>{<br>  &quot;users&quot;: [<br>    {&quot;name&quot;: &quot;Ali&quot;, &quot;cityId&quot;: 1},<br>    {&quot;name&quot;: &quot;Veli&quot;, &quot;cityId&quot;: 1}<br>  ],<br>  &quot;cities&quot;: {&quot;1&quot;: {&quot;name&quot;: &quot;İstanbul&quot;, &quot;country&quot;: &quot;Türkiye&quot;}}<br>}</pre><p><strong>2. Kısa Anahtar İsimleri:</strong></p><pre>// Kötü (verbose keys)<br>{&quot;user_identification_number&quot;: 123}<br><br>// İyi (short keys)<br>{&quot;uid&quot;: 123}</pre><p><strong>3. Null Değerlerin Atlanması:</strong></p><pre>// Kötü<br>{&quot;name&quot;: &quot;Ali&quot;, &quot;middleName&quot;: null, &quot;surname&quot;: &quot;Yılmaz&quot;}<br>// İyi<br>{&quot;name&quot;: &quot;Ali&quot;, &quot;surname&quot;: &quot;Yılmaz&quot;}</pre><h3>📈 Büyük Veri Setleri</h3><p><strong>Streaming JSON:</strong></p><ul><li><strong>JSONStream</strong> (Node.js): Büyük dosyaları parça parça işler</li><li><strong>Oboe.js</strong>: Tarayıcıda progressive parsing</li><li><strong>SAX Parser</strong>: Event-driven parsing</li></ul><p><strong>Pagination Stratejileri:</strong></p><pre>{<br>  &quot;data&quot;: [...],<br>  &quot;pagination&quot;: {<br>    &quot;page&quot;: 1,<br>    &quot;limit&quot;: 100,<br>    &quot;total&quot;: 5000,<br>    &quot;hasNext&quot;: true<br>  }<br>}</pre><h3>🌐 Network Transfer</h3><p><strong>HTTP Optimizasyonları:</strong></p><ul><li><strong>HTTP/2</strong>: Paralel yükleme</li><li><strong>Server Push</strong>: İlgili verileri önceden gönder</li><li><strong>Cache-Control</strong>: Akıllı caching</li><li><strong>ETag</strong>: Koşullu istekler</li></ul><p><strong>CDN Kullanımı:</strong></p><ul><li>Static JSON dosyaları için ideal</li><li>Edge caching ile düşük latency</li><li>Bandwidth tasarrufu</li></ul><h3>🔍 Monitoring ve Analiz</h3><p><strong>Boyut Tracking:</strong></p><ul><li>Bundle analyzer kullanın</li><li>Network tab’da transfer boyutlarını izleyin</li><li>Production’da gzip compression aktif mi kontrol edin</li></ul><p><strong>Performance Monitoring:</strong></p><ul><li>Parse sürelerini ölçün</li><li>Memory leaks kontrol edin</li><li>Large object lifecycle yönetin</li></ul><h3>🎯 En İyi Uygulamalar</h3><ol><li><strong>Development’da</strong>: Pretty-print kullanın</li><li><strong>Production’da</strong>: Minify + Gzip</li><li><strong>API Design’da</strong>: Tutarlı field isimleri</li><li><strong>Large Data</strong>: Pagination + lazy loading</li><li><strong>Caching</strong>: Akıllı cache stratejisi</li><li><strong>Monitoring</strong>: Boyut ve performans metrikleri</li></ol><p>Bu bilgiler ışığında JSON dosyalarınızı optimize edebilir ve uygulamanızın performansını önemli ölçüde artırabilirsiniz!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ea0f1003887" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[.NET global hata yönetimi.]]></title>
            <link>https://emrecglar.medium.com/net-global-hata-y%C3%B6netimi-8a43de4cb800?source=rss-9d515996c3ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a43de4cb800</guid>
            <dc:creator><![CDATA[emrecglar]]></dc:creator>
            <pubDate>Sun, 03 Aug 2025 20:46:33 GMT</pubDate>
            <atom:updated>2025-08-03T20:46:33.501Z</atom:updated>
            <content:encoded><![CDATA[<h3>Error details:</h3><p>bir sınıf oluşturalım. bir hata olduğunda status kodlarını vs görebilelim diye kullanacağız.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*UOE2kAYXzZrjlMqFMJprWg.png" /><figcaption>ToString()’i override edeceğiz. this ile class’ın tamamını ilgilendiririz serialize edeceğiz.</figcaption></figure><p>Serialize nedir = bu nesneyi serialize edersek eğer o zaman</p><p>{Statuscode: 200(gibi),message:”…”} gibi bir yapıya çeviririz. json yapısına çeviririz class’ımızı.</p><h4>Use Exception Handler:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T5BT3Adje7ezBmDE9utYjQ.png" /><figcaption>Buradaki this WebApplication app yapısı şunun için kullanıldı normalde Program.cs’te app.UseExceptionHandler yapacağımıza kendi class’ımızın içerisinde pipeline’a middleware ekleyebilir oluyoruz böylece Program.cs’i uzatmayıp hemde ona dışarıdan ulaşabiliyoruz. Böylece programlarımızı parça parça bölebilir oluyoruz. class static böylece metotlarıda static olacak. Extend edeceğimiz şeyi this ile çağırırız. IloggerService ilede logger’ı çağıracağız. appError’u veriyoruz input olarak sonra appError.Run() diyerek kullanıyoruz bunu. sonra içerisinde async context =&gt; diyerek bunu input olarak vermiş olacağız. ve context’i kullanacağız.</figcaption></figure><h4>Yapılandırma:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*LLlX3CHo_fkKAyAMI-x1UQ.png" /><figcaption>Biz burada app’ten sonra servis’e ihtiyaç duyduk çünkü yukarıdaki class’ta app üzerinde işlem yaptık ama servise ihtiyacımız var o zaman bu şekilde çağırarak ekleriz Program.cs içerisinde.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*DTkLtWWwjly8tbVC6M4Ggw.png" /><figcaption>ek olarak bunu ekledik. bunun amacı şudur: app.UseHsts() Nedir? Bu metot, web uygulamanıza <strong>HSTS (HTTP Strict Transport Security)</strong> başlığını ekleyen bir ara katmandır (middleware). HSTS, bir tarayıcıya (Chrome, Firefox vb.) şunu söyler: “<strong>Bu siteye bir sonraki gelişinde SADECE güvenli olan </strong><strong>https protokolü üzerinden bağlan. Asla güvensiz olan </strong><strong>http&#39;yi deneme!</strong>&quot; <strong>Bunun Faydası Nedir?</strong> Kullanıcılar sitenize http://www.orneksite.com gibi güvensiz bir adresle girmeye çalıştığında, araya siber saldırganlar girerek bilgileri çalabilir (Man-in-the-middle attack). HSTS sayesinde, tarayıcı bu güvensiz isteği sunucuya hiç göndermeden, <strong>doğrudan kendisi </strong><strong>https://www.orneksite.com adresine çevirir.</strong> Bu, kullanıcıyı ve verilerini daha en başından korur.</figcaption></figure><h3>Try-catch bloklarının kaldırılması:</h3><p>iş hattı yapısındaki değişimle try catch kullanmamıza gerek kalmayacak.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*p1F6bw00gVycAYZeRx45-A.png" /><figcaption>Rest yapısında isteklerimiz httpmodules ve handlers gibi yapılardan geçer. (Turuncu alan pipeline) isteklerimiz sırasıyla geçerler. ve response’ye dönüşüp geri gelirler istek attığımız yere. Hataları yönettiğimiz bir middleware ekledik hataları merkezi olarak yöneteceğiz böylece Controller’larda try catch yapısı kullanmaya gerek kalmayacak.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*Ygrz1OOu8wXYJXxdi9mNGA.png" /><figcaption>Bunun gibi try-catchsiz bir biçimde çalışacaklar.</figcaption></figure><p>Debugsuz çalıştırırsak sanki canlıda gibi davranır projemiz.</p><h3>Not found Exception:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*L4cQOuc20uWejGAzrp8Snw.png" /><figcaption>Bir abstract exception class’ı belirledik. ve ek olarak şunu yapıyoruz burada base(message) diyerek string messagedeki elimize geçen mesajı base class’a aktarıyoruz bu yapı ile.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*tyQ0XYLa4O-PEhHGmll5UA.png" /><figcaption>Burada da biz kalıtım yolu ile kendimiz özelleştirdik sealed ile bu class’ı kalıtım veremez hale getirdik. :ExceptionNotFound’u implemente ettik ama constructorumuz ne abstract ExceptionNotFound constructoru gibi davrandı id alıyor ve base’e istediğini yolluyor.</figcaption></figure><p>class’ın adı BookNotFoundException olmalı.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*FcTHprzVbmVVZY_saWlVyQ.png" /><figcaption>middelewareye eklemesini yaptık böylece kullanabiliriz. özetle response’nın dönüş kodunu değiştirelim switch ile notfound gelirse o zaman 404 gelicek.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*Y6z2E8PHAHNMXJ7YllXN6Q.png" /><figcaption>burada şunu dedik dönecek statuscode’u değiştirelim dedik.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*-sfWyw-_mby5eXonF0K0eg.png" /><figcaption>bu satırda şunu dedik Notfound gelirse 404 dön BookNotFound olabilir CategoryNotFound olursa onlar çalışacak bu yapı ile.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*YOdaht7i2rIAeBmhVovSiw.png" /><figcaption>Buradaki şey ise hiçbiri gelmezse bu 500 kodu çalışsın dedik.</figcaption></figure><h3>Refactoring:</h3><p>Bir çıktı alabilmek için kullanacağız.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*ldtl0NkxwXGoJ83--AWZ9w.png" /><figcaption>buradaki controller içerisinde biz istediğimiz o hatayı fırlatabiliriz throw new ile istediğimiz gibi özelleştirerek kullanabiliriz bu yapıyı.</figcaption></figure><p>Hata fırlatma işlemini servistede yapabiliriz yapı şöyle çalışır mesela servisin çalıştırdığı şey servise hata fırlattı serviste alır onu controller’a fırlatır ve controllerda yakalanır yani sorun olmaz sadece o ana kadar çalışan metotlar hata fırlattığı an durur devam etmez.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*YHuM_3cq7ijwkuHQOfutQQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*6-kQg-brTve8J9zTHRTcLw.png" /></figure><p>Böylece bir hata olursa Servisten Controller’a fırlatılacak middleware ilede onu yakalayabileceğiz. try catch blokları olmadan bunu yapabiliriz artık.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a43de4cb800" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Asp.Net Core Security(Güvenlik)]]></title>
            <link>https://emrecglar.medium.com/asp-net-core-security-g%C3%BCvenlik-73d206ea3108?source=rss-9d515996c3ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/73d206ea3108</guid>
            <dc:creator><![CDATA[emrecglar]]></dc:creator>
            <pubDate>Tue, 15 Jul 2025 22:23:30 GMT</pubDate>
            <atom:updated>2025-10-18T21:17:31.744Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data protection(Veri koruması):</h3><p>Neden ihtiyaç duyarız? Bazı verileri dış dünyaya açmak istemeyiz. Mesela Tc kimlik no’sunun query string’te olmasını istemeyiz. Bu konuda Data Protection yapısı kullanırız.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*KQbayh-4S48inUg0hmrpeg.png" /><figcaption>Dış dünyaya açmak istemediğimiz property’leri şifreleyerek dış dünyaya açabiliriz. 26&#39;nın şifrelenmiş hali yukarıdadır. böylece anlaşılabilir bir yapı sunmayız.</figcaption></figure><p>IDataProtector interfacesi kullanırız asp ile gömülü olarak gelir. Protect() ile şifreleme UnProtect() ile ise deşifreleme yaparız.</p><p>.NET Data Protection API, ASP.NET Core’da hassas verileri şifrelemek ve korumak için tasarlanmış bir sistemdir. Özellikle authentication cookies, anti-forgery tokens, session data gibi geçici verilerin güvenliğini sağlar.</p><h4>Temel Amaç</h4><p><strong>Automatic Key Management</strong>: Şifreleme anahtarlarını otomatik yönetir <strong>Time-based Protection</strong>: Verilerin belirli süre sonra geçersiz olmasını sağlar <strong>Purpose Isolation</strong>: Farklı amaçlar için farklı şifreleme anahtarları kullanır <strong>Cross-platform</strong>: Farklı sunucularda aynı verilerin çözülebilmesi</p><h4>Temel Kullanım</h4><pre>public class DataProtectionService<br>{<br>    private readonly IDataProtector _protector;<br>    <br>    public DataProtectionService(IDataProtectionProvider provider)<br>    {<br>        // Purpose string - farklı amaçlar için farklı şifreler<br>        _protector = provider.CreateProtector(&quot;UserData.PersonalInfo&quot;);<br>    }<br>    <br>    public string ProtectData(string plainText)<br>    {<br>        return _protector.Protect(plainText);<br>    }<br>    <br>    public string UnprotectData(string protectedData)<br>    {<br>        try<br>        {<br>            return _protector.Unprotect(protectedData);<br>        }<br>        catch (CryptographicException)<br>        {<br>            // Şifre çözülemedi - veri bozuk veya süresi dolmuş<br>            return null;<br>        }<br>    }<br>}<br><br>// Registration<br>builder.Services.AddDataProtection();<br>builder.Services.AddScoped&lt;DataProtectionService&gt;();</pre><h4>Time-based Protection</h4><pre>public class TimeLimitedProtectionService<br>{<br>    private readonly ITimeLimitedDataProtector _protector;<br>    <br>    public TimeLimitedProtectionService(IDataProtectionProvider provider)<br>    {<br>        var baseProtector = provider.CreateProtector(&quot;TimeSensitive.Data&quot;);<br>        _protector = baseProtector.ToTimeLimitedDataProtector();<br>    }<br>    <br>    public string ProtectWithExpiry(string data, TimeSpan lifetime)<br>    {<br>        return _protector.Protect(data, lifetime);<br>    }<br>    <br>    public string UnprotectWithExpiry(string protectedData)<br>    {<br>        try<br>        {<br>            return _protector.Unprotect(protectedData);<br>        }<br>        catch (CryptographicException ex) when (ex.Message.Contains(&quot;expired&quot;))<br>        {<br>            // Veri süresi dolmuş<br>            return null;<br>        }<br>    }<br>}<br><br>// Kullanım<br>var service = new TimeLimitedProtectionService(provider);<br>var protected = service.ProtectWithExpiry(&quot;sensitive data&quot;, TimeSpan.FromHours(1));<br>// 1 saat sonra bu veri artık çözülemez</pre><h4>Configuration ve Key Management</h4><pre>// Program.cs - Temel configuration<br>builder.Services.AddDataProtection()<br>    .SetApplicationName(&quot;MyApp&quot;) // Farklı uygulamalar arası paylaşım için<br>    .PersistKeysToFileSystem(new DirectoryInfo(&quot;/keys&quot;)) // Anahtar depolama<br>    .SetDefaultKeyLifetime(TimeSpan.FromDays(90)) // Anahtar yaşam süresi<br>    .AddKeyEscrowSink&lt;MyKeyEscrowSink&gt;(); // Anahtar yedekleme<br><br><br>// Azure Key Vault ile<br>builder.Services.AddDataProtection()<br>    .PersistKeysToAzureBlobStorage(connectionString, containerName, blobName)<br>    .ProtectKeysWithAzureKeyVault(keyIdentifier, credential);<br>// Redis ile<br>builder.Services.AddDataProtection()<br>    .PersistKeysToStackExchangeRedis(redis, &quot;DataProtection-Keys&quot;);</pre><h4>Purpose Hierarchy</h4><pre>public class HierarchicalProtectionService<br>{<br>    private readonly IDataProtectionProvider _provider;<br>    <br>    public HierarchicalProtectionService(IDataProtectionProvider provider)<br>    {<br>        _provider = provider;<br>    }<br>    <br>    public string ProtectUserData(int userId, string data)<br>    {<br>        // Hiyerarşik purpose - her kullanıcı için farklı şifre<br>        var protector = _provider.CreateProtector(&quot;Users&quot;, userId.ToString(), &quot;PersonalData&quot;);<br>        return protector.Protect(data);<br>    }<br>    <br>    public string ProtectSessionData(string sessionId, string data)<br>    {<br>        var protector = _provider.CreateProtector(&quot;Sessions&quot;, sessionId, &quot;Temporary&quot;);<br>        return protector.Protect(data);<br>    }<br>    <br>    public string ProtectPaymentData(string data)<br>    {<br>        // En kritik veriler için ayrı purpose<br>        var protector = _provider.CreateProtector(&quot;Payment&quot;, &quot;CreditCard&quot;, &quot;Sensitive&quot;);<br>        return protector.Protect(data);<br>    }<br>}</pre><h4>Custom Data Protection</h4><pre>public class SecureUserTokenService<br>{<br>    private readonly ITimeLimitedDataProtector _protector;<br>    private readonly ILogger&lt;SecureUserTokenService&gt; _logger;<br>    <br>    public SecureUserTokenService(IDataProtectionProvider provider, ILogger&lt;SecureUserTokenService&gt; logger)<br>    {<br>        var baseProtector = provider.CreateProtector(&quot;UserTokens.Authentication&quot;);<br>        _protector = baseProtector.ToTimeLimitedDataProtector();<br>        _logger = logger;<br>    }<br>    <br>    public string GeneratePasswordResetToken(int userId)<br>    {<br>        var tokenData = new<br>        {<br>            UserId = userId,<br>            Purpose = &quot;PasswordReset&quot;,<br>            Timestamp = DateTimeOffset.UtcNow<br>        };<br>        <br>        var json = JsonSerializer.Serialize(tokenData);<br>        return _protector.Protect(json, TimeSpan.FromHours(1)); // 1 saatlik token<br>    }<br>    <br>    public (bool IsValid, int UserId) ValidatePasswordResetToken(string token)<br>    {<br>        try<br>        {<br>            var json = _protector.Unprotect(token);<br>            var tokenData = JsonSerializer.Deserialize&lt;dynamic&gt;(json);<br>            <br>            return (true, tokenData.UserId);<br>        }<br>        catch (CryptographicException ex)<br>        {<br>            _logger.LogWarning(&quot;Invalid password reset token: {Error}&quot;, ex.Message);<br>            return (false, 0);<br>        }<br>    }<br>}</pre><h4>Cookie Protection</h4><pre>// ASP.NET Core otomatik olarak cookie&#39;leri korur<br>builder.Services.ConfigureApplicationCookie(options =&gt;<br>{<br>    options.Cookie.Name = &quot;MyApp.Auth&quot;;<br>    options.Cookie.HttpOnly = true;<br>    options.Cookie.SecurePolicy = CookieSecurePolicy.Always;<br>    options.DataProtectionProvider = provider; // Custom provider<br>});<br><br><br>// Custom cookie protection<br>public class SecureCookieService<br>{<br>    private readonly IDataProtector _protector;<br>    <br>    public SecureCookieService(IDataProtectionProvider provider)<br>    {<br>        _protector = provider.CreateProtector(&quot;Cookies.UserPreferences&quot;);<br>    }<br>    <br>    public void SetSecureCookie(HttpContext context, string name, object value, TimeSpan? expiry = null)<br>    {<br>        var json = JsonSerializer.Serialize(value);<br>        var protectedValue = expiry.HasValue <br>            ? _protector.ToTimeLimitedDataProtector().Protect(json, expiry.Value)<br>            : _protector.Protect(json);<br>            <br>        context.Response.Cookies.Append(name, protectedValue, new CookieOptions<br>        {<br>            HttpOnly = true,<br>            Secure = true,<br>            SameSite = SameSiteMode.Strict<br>        });<br>    }<br>    <br>    public T GetSecureCookie&lt;T&gt;(HttpContext context, string name)<br>    {<br>        if (!context.Request.Cookies.TryGetValue(name, out var protectedValue))<br>            return default(T);<br>            <br>        try<br>        {<br>            var json = _protector.Unprotect(protectedValue);<br>            return JsonSerializer.Deserialize&lt;T&gt;(json);<br>        }<br>        catch (CryptographicException)<br>        {<br>            return default(T);<br>        }<br>    }<br>}</pre><h4>Anti-Forgery Token Protection</h4><p>csharp</p><pre>// ASP.NET Core otomatik olarak anti-forgery token&#39;ları korur<br>builder.Services.AddAntiforgery(options =&gt;<br>{<br>    options.Cookie.Name = &quot;__RequestVerificationToken&quot;;<br>    options.Cookie.HttpOnly = true;<br>    options.Cookie.SecurePolicy = CookieSecurePolicy.Always;<br>});<br><br><br><br><br><br><br>// Custom implementation<br>public class CustomAntiForgeryService<br>{<br>    private readonly ITimeLimitedDataProtector _protector;<br>    <br>    public CustomAntiForgeryService(IDataProtectionProvider provider)<br>    {<br>        var baseProtector = provider.CreateProtector(&quot;AntiForgery.Custom&quot;);<br>        _protector = baseProtector.ToTimeLimitedDataProtector();<br>    }<br>    <br>    public string GenerateToken(ClaimsPrincipal user)<br>    {<br>        var tokenData = new<br>        {<br>            UserId = user.FindFirst(ClaimTypes.NameIdentifier)?.Value,<br>            UserName = user.Identity.Name,<br>            Timestamp = DateTimeOffset.UtcNow<br>        };<br>        <br>        var json = JsonSerializer.Serialize(tokenData);<br>        return _protector.Protect(json, TimeSpan.FromMinutes(30));<br>    }<br>    <br>    public bool ValidateToken(string token, ClaimsPrincipal user)<br>    {<br>        try<br>        {<br>            var json = _protector.Unprotect(token);<br>            var tokenData = JsonSerializer.Deserialize&lt;dynamic&gt;(json);<br>            <br>            return tokenData.UserId == user.FindFirst(ClaimTypes.NameIdentifier)?.Value;<br>        }<br>        catch (CryptographicException)<br>        {<br>            return false;<br>        }<br>    }<br>}</pre><h4>Production Configuration</h4><pre>// Production için güvenli configuration<br>if (builder.Environment.IsProduction())<br>{<br>    builder.Services.AddDataProtection()<br>        .SetApplicationName(&quot;MyProductionApp&quot;)<br>        .PersistKeysToAzureBlobStorage(connectionString, container, blob)<br>        .ProtectKeysWithAzureKeyVault(keyVaultKeyId, credential)<br>        .SetDefaultKeyLifetime(TimeSpan.FromDays(30))<br>        .AddKeyEscrowSink&lt;ProductionKeyEscrowSink&gt;();<br>}<br>else<br>{<br>    // Development için basit configuration<br>    builder.Services.AddDataProtection()<br>        .SetApplicationName(&quot;MyDevApp&quot;)<br>        .PersistKeysToFileSystem(new DirectoryInfo(&quot;./keys&quot;));<br>}</pre><h4>Key Rotation ve Management</h4><pre>public class KeyManagementService<br>{<br>    private readonly IKeyManager _keyManager;<br>    <br>    public KeyManagementService(IKeyManager keyManager)<br>    {<br>        _keyManager = keyManager;<br>    }<br>    <br>    public void RotateKeys()<br>    {<br>        // Yeni anahtar oluştur<br>        _keyManager.CreateNewKey(DateTimeOffset.Now, DateTimeOffset.Now.AddDays(90));<br>    }<br>    <br>    public void RevokeCompromisedKey(Guid keyId, string reason)<br>    {<br>        _keyManager.RevokeKey(keyId, reason);<br>    }<br>    <br>    public IReadOnlyCollection&lt;IKey&gt; GetAllKeys()<br>    {<br>        return _keyManager.GetAllKeys();<br>    }<br>}</pre><h4>Avantajlar</h4><p><strong>Automatic Management</strong>: Manuel anahtar yönetimi gerektirmez <strong>Cross-machine</strong>: Cluster ortamlarında paylaşılabilir <strong>Time-based Security</strong>: Otomatik süre sonu kontrolü <strong>Purpose Isolation</strong>: Farklı amaçlar için ayrı güvenlik <strong>Platform Integration</strong>: Azure, AWS gibi cloud provider’larla entegrasyon</p><p>Data Protection API, ASP.NET Core uygulamalarında güvenli veri işleme için vazgeçilmez bir araçtır ve framework’ün birçok güvenlik özelliğinin temelini oluşturur.</p><h3>WhiteList/BlackList IP control:</h3><p>Gelen istekleri whitelist ve blacklist’e alarak istek kontrolü yapabiliriz. Sadece belli bir adresten gelen veya gelmeyen istekleri kullanabilmezi sağlayabiliriz. İki farklı yolla yapabiliriz uygulama seviyesinde ve Controller/method seviyesinde.</p><p>IP tabanlı erişim kontrolü, Web API’lerde güvenlik için kullanılan temel yöntemlerden biridir. Belirli IP adreslerinden gelen istekleri kabul etme (whitelist) veya reddetme (blacklist) işlemidir.</p><h3>Temel Kavramlar</h3><p><strong>Whitelist (İzin Listesi)</strong>: Sadece listede bulunan IP’lere erişim izni verir. Daha güvenli yaklaşım. <strong>Blacklist (Yasaklı Listesi)</strong>: Listede bulunan IP’leri bloklar, diğerlerine izin verir. Daha esnek yaklaşım.</p><h3>Middleware Implementation</h3><pre>public class IPFilteringMiddleware<br>{<br>    private readonly RequestDelegate _next;<br>    private readonly IPFilteringOptions _options;<br>    private readonly ILogger&lt;IPFilteringMiddleware&gt; _logger;<br>    <br>    public IPFilteringMiddleware(<br>        RequestDelegate next, <br>        IOptions&lt;IPFilteringOptions&gt; options,<br>        ILogger&lt;IPFilteringMiddleware&gt; logger)<br>    {<br>        _next = next;<br>        _options = options.Value;<br>        _logger = logger;<br>    }<br>    <br>    public async Task InvokeAsync(HttpContext context)<br>    {<br>        var clientIP = GetClientIPAddress(context);<br>        <br>        if (!IsIPAllowed(clientIP))<br>        {<br>            _logger.LogWarning(&quot;Access denied for IP: {IP}&quot;, clientIP);<br>            context.Response.StatusCode = 403;<br>            await context.Response.WriteAsync(&quot;Access denied&quot;);<br>            return;<br>        }<br>        <br>        await _next(context);<br>    }<br>    <br>    private IPAddress GetClientIPAddress(HttpContext context)<br>    {<br>        // Proxy/Load Balancer arkasındaki gerçek IP&#39;yi al<br>        var xForwardedFor = context.Request.Headers[&quot;X-Forwarded-For&quot;].FirstOrDefault();<br>        if (!string.IsNullOrEmpty(xForwardedFor))<br>        {<br>            var ips = xForwardedFor.Split(&#39;,&#39;);<br>            if (IPAddress.TryParse(ips[0].Trim(), out var ip))<br>                return ip;<br>        }<br>        <br>        var xRealIP = context.Request.Headers[&quot;X-Real-IP&quot;].FirstOrDefault();<br>        if (!string.IsNullOrEmpty(xRealIP) &amp;&amp; IPAddress.TryParse(xRealIP, out var realIP))<br>            return realIP;<br>        <br>        return context.Connection.RemoteIpAddress ?? IPAddress.None;<br>    }<br>    <br>    private bool IsIPAllowed(IPAddress clientIP)<br>    {<br>        // Whitelist kontrolü (varsa)<br>        if (_options.Whitelist?.Any() == true)<br>        {<br>            return _options.Whitelist.Any(allowedIP =&gt; IsIPInRange(clientIP, allowedIP));<br>        }<br>        <br>        // Blacklist kontrolü<br>        if (_options.Blacklist?.Any() == true)<br>        {<br>            return !_options.Blacklist.Any(blockedIP =&gt; IsIPInRange(clientIP, blockedIP));<br>        }<br>        <br>        // Hiç liste yoksa tüm IP&#39;lere izin ver<br>        return true;<br>    }<br>    <br>    private bool IsIPInRange(IPAddress clientIP, string allowedRange)<br>    {<br>        if (allowedRange.Contains(&#39;/&#39;))<br>        {<br>            // CIDR notation: 192.168.1.0/24<br>            return IsIPInCIDRRange(clientIP, allowedRange);<br>        }<br>        else if (allowedRange.Contains(&#39;-&#39;))<br>        {<br>            // Range notation: 192.168.1.1-192.168.1.100<br>            return IsIPInIPRange(clientIP, allowedRange);<br>        }<br>        else<br>        {<br>            // Tek IP adresi<br>            return IPAddress.TryParse(allowedRange, out var allowedIP) &amp;&amp; clientIP.Equals(allowedIP);<br>        }<br>    }<br>    <br>    private bool IsIPInCIDRRange(IPAddress clientIP, string cidrRange)<br>    {<br>        var parts = cidrRange.Split(&#39;/&#39;);<br>        if (parts.Length != 2 || !IPAddress.TryParse(parts[0], out var networkIP) || !int.TryParse(parts[1], out var prefixLength))<br>            return false;<br>        <br>        var networkBytes = networkIP.GetAddressBytes();<br>        var clientBytes = clientIP.GetAddressBytes();<br>        <br>        if (networkBytes.Length != clientBytes.Length)<br>            return false;<br>        <br>        var bytesToCheck = prefixLength / 8;<br>        var bitsToCheck = prefixLength % 8;<br>        <br>        // Tam byte&#39;ları kontrol et<br>        for (int i = 0; i &lt; bytesToCheck; i++)<br>        {<br>            if (networkBytes[i] != clientBytes[i])<br>                return false;<br>        }<br>        <br>        // Kalan bitleri kontrol et<br>        if (bitsToCheck &gt; 0 &amp;&amp; bytesToCheck &lt; networkBytes.Length)<br>        {<br>            var mask = (byte)(0xFF &lt;&lt; (8 - bitsToCheck));<br>            if ((networkBytes[bytesToCheck] &amp; mask) != (clientBytes[bytesToCheck] &amp; mask))<br>                return false;<br>        }<br>        <br>        return true;<br>    }<br>    <br>    private bool IsIPInIPRange(IPAddress clientIP, string ipRange)<br>    {<br>        var parts = ipRange.Split(&#39;-&#39;);<br>        if (parts.Length != 2 || !IPAddress.TryParse(parts[0], out var startIP) || !IPAddress.TryParse(parts[1], out var endIP))<br>            return false;<br>        <br>        var clientBytes = clientIP.GetAddressBytes();<br>        var startBytes = startIP.GetAddressBytes();<br>        var endBytes = endIP.GetAddressBytes();<br>        <br>        if (clientBytes.Length != startBytes.Length || clientBytes.Length != endBytes.Length)<br>            return false;<br>        <br>        var clientInt = BitConverter.ToUInt32(clientBytes.Reverse().ToArray(), 0);<br>        var startInt = BitConverter.ToUInt32(startBytes.Reverse().ToArray(), 0);<br>        var endInt = BitConverter.ToUInt32(endBytes.Reverse().ToArray(), 0);<br>        <br>        return clientInt &gt;= startInt &amp;&amp; clientInt &lt;= endInt;<br>    }<br>}</pre><pre>public class IPFilteringOptions<br>{<br>    public List&lt;string&gt; Whitelist { get; set; } = new();<br>    public List&lt;string&gt; Blacklist { get; set; } = new();<br>    public bool BypassForLocalhost { get; set; } = true;<br>}</pre><h3>Configuration</h3><pre>// appsettings.json<br>{<br>  &quot;IPFiltering&quot;: {<br>    &quot;Whitelist&quot;: [<br>      &quot;192.168.1.0/24&quot;,    // Local network<br>      &quot;10.0.0.1&quot;,          // Specific IP<br>      &quot;203.0.113.0/24&quot;     // Office network<br>    ],<br>    &quot;Blacklist&quot;: [<br>      &quot;192.168.1.100&quot;,     // Blocked specific IP<br>      &quot;172.16.0.0/16&quot;      // Blocked network<br>    ],<br>    &quot;BypassForLocalhost&quot;: true<br>  }<br>}</pre><pre>// Program.cs<br>builder.Services.Configure&lt;IPFilteringOptions&gt;(<br>    builder.Configuration.GetSection(&quot;IPFiltering&quot;));</pre><pre>builder.Services.AddSingleton&lt;IPFilteringMiddleware&gt;();</pre><pre>var app = builder.Build();<br>app.UseMiddleware&lt;IPFilteringMiddleware&gt;();</pre><h3>Action Filter Implementation</h3><pre>public class IPFilterAttribute : ActionFilterAttribute<br>{<br>    private readonly string[] _allowedIPs;<br>    private readonly string[] _blockedIPs;<br>    <br>    public IPFilterAttribute(params string[] allowedIPs)<br>    {<br>        _allowedIPs = allowedIPs;<br>    }<br>    <br>    public IPFilterAttribute(string[] allowedIPs = null, string[] blockedIPs = null)<br>    {<br>        _allowedIPs = allowedIPs ?? Array.Empty&lt;string&gt;();<br>        _blockedIPs = blockedIPs ?? Array.Empty&lt;string&gt;();<br>    }<br>    <br>    public override void OnActionExecuting(ActionExecutingContext context)<br>    {<br>        var clientIP = GetClientIP(context.HttpContext);<br>        <br>        // Whitelist kontrolü<br>        if (_allowedIPs.Any() &amp;&amp; !_allowedIPs.Any(ip =&gt; IsIPAllowed(clientIP, ip)))<br>        {<br>            context.Result = new ForbidResult();<br>            return;<br>        }<br>        <br>        // Blacklist kontrolü<br>        if (_blockedIPs.Any() &amp;&amp; _blockedIPs.Any(ip =&gt; IsIPAllowed(clientIP, ip)))<br>        {<br>            context.Result = new ForbidResult();<br>            return;<br>        }<br>        <br>        base.OnActionExecuting(context);<br>    }<br>    <br>    private IPAddress GetClientIP(HttpContext context)<br>    {<br>        // Middleware&#39;deki aynı logic<br>        var xForwardedFor = context.Request.Headers[&quot;X-Forwarded-For&quot;].FirstOrDefault();<br>        if (!string.IsNullOrEmpty(xForwardedFor))<br>        {<br>            var ips = xForwardedFor.Split(&#39;,&#39;);<br>            if (IPAddress.TryParse(ips[0].Trim(), out var ip))<br>                return ip;<br>        }<br>        <br>        return context.Connection.RemoteIpAddress ?? IPAddress.None;<br>    }<br>    <br>    private bool IsIPAllowed(IPAddress clientIP, string allowedIP)<br>    {<br>        // Aynı IP kontrol logic&#39;i<br>        return IPAddress.TryParse(allowedIP, out var parsed) &amp;&amp; clientIP.Equals(parsed);<br>    }<br>}</pre><pre>// Controller&#39;da kullanım<br>[ApiController]<br>[Route(&quot;api/[controller]&quot;)]<br>public class AdminController : ControllerBase<br>{<br>    [HttpGet(&quot;users&quot;)]<br>    [IPFilter(&quot;192.168.1.0/24&quot;, &quot;10.0.0.1&quot;)] // Sadece office network<br>    public async Task&lt;IActionResult&gt; GetUsers()<br>    {<br>        // Admin işlemleri<br>        return Ok();<br>    }<br>    <br>    [HttpPost(&quot;maintenance&quot;)]<br>    [IPFilter(allowedIPs: new[] { &quot;192.168.1.100&quot; })] // Sadece admin IP<br>    public async Task&lt;IActionResult&gt; StartMaintenance()<br>    {<br>        return Ok();<br>    }<br>}</pre><h3>Database-driven IP Control</h3><pre>public interface IIPFilterService<br>{<br>    Task&lt;bool&gt; IsIPAllowedAsync(IPAddress ip);<br>    Task AddToWhitelistAsync(string ip, string description);<br>    Task AddToBlacklistAsync(string ip, string description);<br>    Task RemoveFromWhitelistAsync(string ip);<br>    Task RemoveFromBlacklistAsync(string ip);<br>}<br><br><br>public class IPFilterService : IIPFilterService<br>{<br>    private readonly AppDbContext _context;<br>    private readonly IMemoryCache _cache;<br>    private readonly ILogger&lt;IPFilterService&gt; _logger;<br>    <br>    public IPFilterService(AppDbContext context, IMemoryCache cache, ILogger&lt;IPFilterService&gt; logger)<br>    {<br>        _context = context;<br>        _cache = cache;<br>        _logger = logger;<br>    }<br>    <br>    public async Task&lt;bool&gt; IsIPAllowedAsync(IPAddress ip)<br>    {<br>        var cacheKey = $&quot;ip_filter_{ip}&quot;;<br>        <br>        if (_cache.TryGetValue(cacheKey, out bool cached))<br>            return cached;<br>        <br>        // Whitelist kontrolü<br>        var whitelistExists = await _context.IPWhitelist.AnyAsync();<br>        if (whitelistExists)<br>        {<br>            var isWhitelisted = await _context.IPWhitelist<br>                .AnyAsync(w =&gt; w.IPAddress == ip.ToString() || IsIPInRange(ip, w.IPRange));<br>            <br>            _cache.Set(cacheKey, isWhitelisted, TimeSpan.FromMinutes(5));<br>            return isWhitelisted;<br>        }<br>        <br>        // Blacklist kontrolü<br>        var isBlacklisted = await _context.IPBlacklist<br>            .AnyAsync(b =&gt; b.IPAddress == ip.ToString() || IsIPInRange(ip, b.IPRange));<br>        <br>        var result = !isBlacklisted;<br>        _cache.Set(cacheKey, result, TimeSpan.FromMinutes(5));<br>        <br>        return result;<br>    }<br>    <br>    public async Task AddToWhitelistAsync(string ip, string description)<br>    {<br>        var entry = new IPWhitelistEntry<br>        {<br>            IPAddress = ip,<br>            Description = description,<br>            CreatedAt = DateTime.UtcNow<br>        };<br>        <br>        _context.IPWhitelist.Add(entry);<br>        await _context.SaveChangesAsync();<br>        <br>        _cache.Remove($&quot;ip_filter_{ip}&quot;);<br>        _logger.LogInformation(&quot;IP {IP} added to whitelist: {Description}&quot;, ip, description);<br>    }<br>    <br>    public async Task AddToBlacklistAsync(string ip, string description)<br>    {<br>        var entry = new IPBlacklistEntry<br>        {<br>            IPAddress = ip,<br>            Description = description,<br>            CreatedAt = DateTime.UtcNow<br>        };<br>        <br>        _context.IPBlacklist.Add(entry);<br>        await _context.SaveChangesAsync();<br>        <br>        _cache.Remove($&quot;ip_filter_{ip}&quot;);<br>        _logger.LogWarning(&quot;IP {IP} added to blacklist: {Description}&quot;, ip, description);<br>    }<br>}<br>// Entity models<br>public class IPWhitelistEntry<br>{<br>    public int Id { get; set; }<br>    public string IPAddress { get; set; }<br>    public string IPRange { get; set; }<br>    public string Description { get; set; }<br>    public DateTime CreatedAt { get; set; }<br>}<br>public class IPBlacklistEntry<br>{<br>    public int Id { get; set; }<br>    public string IPAddress { get; set; }<br>    public string IPRange { get; set; }<br>    public string Description { get; set; }<br>    public DateTime CreatedAt { get; set; }<br>}</pre><h3>Dynamic IP Management API</h3><pre>[ApiController]<br>[Route(&quot;api/[controller]&quot;)]<br>[Authorize(Roles = &quot;Admin&quot;)]<br>public class IPManagementController : ControllerBase<br>{<br>    private readonly IIPFilterService _ipFilterService;<br>    <br>    public IPManagementController(IIPFilterService ipFilterService)<br>    {<br>        _ipFilterService = ipFilterService;<br>    }<br>    <br>    [HttpPost(&quot;whitelist&quot;)]<br>    public async Task&lt;IActionResult&gt; AddToWhitelist([FromBody] AddIPRequest request)<br>    {<br>        if (!IsValidIP(request.IPAddress))<br>            return BadRequest(&quot;Invalid IP address format&quot;);<br>        <br>        await _ipFilterService.AddToWhitelistAsync(request.IPAddress, request.Description);<br>        return Ok(&quot;IP added to whitelist&quot;);<br>    }<br>    <br>    [HttpPost(&quot;blacklist&quot;)]<br>    public async Task&lt;IActionResult&gt; AddToBlacklist([FromBody] AddIPRequest request)<br>    {<br>        if (!IsValidIP(request.IPAddress))<br>            return BadRequest(&quot;Invalid IP address format&quot;);<br>        <br>        await _ipFilterService.AddToBlacklistAsync(request.IPAddress, request.Description);<br>        return Ok(&quot;IP added to blacklist&quot;);<br>    }<br>    <br>    [HttpDelete(&quot;whitelist/{ip}&quot;)]<br>    public async Task&lt;IActionResult&gt; RemoveFromWhitelist(string ip)<br>    {<br>        await _ipFilterService.RemoveFromWhitelistAsync(ip);<br>        return Ok(&quot;IP removed from whitelist&quot;);<br>    }<br>    <br>    [HttpGet(&quot;check/{ip}&quot;)]<br>    public async Task&lt;IActionResult&gt; CheckIP(string ip)<br>    {<br>        if (!IPAddress.TryParse(ip, out var ipAddress))<br>            return BadRequest(&quot;Invalid IP address&quot;);<br>        <br>        var isAllowed = await _ipFilterService.IsIPAllowedAsync(ipAddress);<br>        return Ok(new { IPAddress = ip, IsAllowed = isAllowed });<br>    }<br>    <br>    private bool IsValidIP(string ip)<br>    {<br>        return IPAddress.TryParse(ip, out _) || IsValidCIDR(ip) || IsValidRange(ip);<br>    }<br>    <br>    private bool IsValidCIDR(string cidr)<br>    {<br>        var parts = cidr.Split(&#39;/&#39;);<br>        return parts.Length == 2 &amp;&amp; <br>               IPAddress.TryParse(parts[0], out _) &amp;&amp; <br>               int.TryParse(parts[1], out var prefix) &amp;&amp; <br>               prefix &gt;= 0 &amp;&amp; prefix &lt;= 32;<br>    }<br>    <br>    private bool IsValidRange(string range)<br>    {<br>        var parts = range.Split(&#39;-&#39;);<br>        return parts.Length == 2 &amp;&amp; <br>               IPAddress.TryParse(parts[0], out _) &amp;&amp; <br>               IPAddress.TryParse(parts[1], out _);<br>    }<br>}</pre><pre>public class AddIPRequest<br>{<br>    public string IPAddress { get; set; }<br>    public string Description { get; set; }<br>}</pre><h3>Rate Limiting ile Kombinasyon</h3><pre>public class IPBasedRateLimitingMiddleware<br>{<br>    private readonly RequestDelegate _next;<br>    private readonly IMemoryCache _cache;<br>    private readonly IIPFilterService _ipFilterService;<br>    <br>    public IPBasedRateLimitingMiddleware(<br>        RequestDelegate next, <br>        IMemoryCache cache,<br>        IIPFilterService ipFilterService)<br>    {<br>        _next = next;<br>        _cache = cache;<br>        _ipFilterService = ipFilterService;<br>    }<br>    <br>    public async Task InvokeAsync(HttpContext context)<br>    {<br>        var clientIP = GetClientIP(context);<br>        <br>        // IP filtering kontrolü<br>        if (!await _ipFilterService.IsIPAllowedAsync(clientIP))<br>        {<br>            context.Response.StatusCode = 403;<br>            return;<br>        }<br>        <br>        // Rate limiting<br>        var key = $&quot;rate_limit_{clientIP}&quot;;<br>        var requests = _cache.GetOrCreate(key, entry =&gt;<br>        {<br>            entry.SlidingExpiration = TimeSpan.FromMinutes(1);<br>            return new List&lt;DateTime&gt;();<br>        });<br>        <br>        var now = DateTime.UtcNow;<br>        requests.RemoveAll(time =&gt; now - time &gt; TimeSpan.FromMinutes(1));<br>        <br>        if (requests.Count &gt;= 100) // 100 requests per minute<br>        {<br>            context.Response.StatusCode = 429;<br>            await context.Response.WriteAsync(&quot;Too many requests&quot;);<br>            return;<br>        }<br>        <br>        requests.Add(now);<br>        await _next(context);<br>    }<br>    <br>    private IPAddress GetClientIP(HttpContext context)<br>    {<br>        // Aynı IP alma logic&#39;i<br>        var xForwardedFor = context.Request.Headers[&quot;X-Forwarded-For&quot;].FirstOrDefault();<br>        if (!string.IsNullOrEmpty(xForwardedFor))<br>        {<br>            var ips = xForwardedFor.Split(&#39;,&#39;);<br>            if (IPAddress.TryParse(ips[0].Trim(), out var ip))<br>                return ip;<br>        }<br>        <br>        return context.Connection.RemoteIpAddress ?? IPAddress.None;<br>    }<br>}</pre><h3>Logging ve Monitoring</h3><pre>public class IPFilteringLogger<br>{<br>    private readonly ILogger&lt;IPFilteringLogger&gt; _logger;<br>    <br>    public IPFilteringLogger(ILogger&lt;IPFilteringLogger&gt; logger)<br>    {<br>        _logger = logger;<br>    }<br>    <br>    public void LogIPBlocked(IPAddress ip, string reason, string endpoint)<br>    {<br>        _logger.LogWarning(&quot;IP {IP} blocked from {Endpoint}. Reason: {Reason}&quot;, <br>                          ip, endpoint, reason);<br>    }<br>    <br>    public void LogSuspiciousActivity(IPAddress ip, string activity)<br>    {<br>        _logger.LogWarning(&quot;Suspicious activity from IP {IP}: {Activity}&quot;, ip, activity);<br>    }<br>    <br>    public void LogIPWhitelisted(IPAddress ip, string addedBy)<br>    {<br>        _logger.LogInformation(&quot;IP {IP} added to whitelist by {User}&quot;, ip, addedBy);<br>    }<br>}</pre><h3>Best Practices</h3><p><strong>Performance</strong>: Cache kullanın, veritabanı sorgularını minimize edin <strong>Security</strong>: Proxy header’larını validate edin <strong>Monitoring</strong>: Blocked request’leri loglamayı unutmayın <strong>Flexibility</strong>: Dynamic IP management sağlayın <strong>Documentation</strong>: IP range formatlarını dokümante edin</p><p>IP filtering, API güvenliğinin temel taşlarından biridir ve diğer güvenlik önlemleriyle birlikte kullanıldığında etkili koruma sağlar.</p><h3>AppSettings’te IPv4 ve IPv6 Whitelist/Blacklist Tanımlama</h3><p>IPv4 ve IPv6 adreslerini appsettings.json’da tanımlarken farklı formatlar ve notasyonlar kullanabilirsiniz. İşte detaylı açıklama:</p><h3>AppSettings.json Konfigürasyonu</h3><pre>{<br>  &quot;IPFiltering&quot;: {<br>    &quot;Whitelist&quot;: [<br>      // IPv4 Tek IP Adresleri<br>      &quot;192.168.1.100&quot;,<br>      &quot;10.0.0.1&quot;,<br>      &quot;172.16.0.5&quot;,<br>      <br>      // IPv4 CIDR Notasyonu (Subnet)<br>      &quot;192.168.1.0/24&quot;,        // 192.168.1.1 - 192.168.1.254<br>      &quot;10.0.0.0/8&quot;,            // 10.0.0.1 - 10.255.255.254<br>      &quot;172.16.0.0/16&quot;,         // 172.16.0.1 - 172.16.255.254<br>      &quot;192.168.0.0/16&quot;,        // 192.168.0.1 - 192.168.255.254<br>      <br>      // IPv4 Range Notasyonu<br>      &quot;192.168.1.1-192.168.1.50&quot;,<br>      &quot;10.0.0.100-10.0.0.200&quot;,<br>      <br>      // IPv6 Tek IP Adresleri<br>      &quot;::1&quot;,                                    // Localhost<br>      &quot;2001:db8::1&quot;,                           // Örnek IPv6<br>      &quot;fe80::1&quot;,                               // Link-local<br>      &quot;2001:0db8:85a3:0000:0000:8a2e:0370:7334&quot;,<br>      <br>      // IPv6 CIDR Notasyonu<br>      &quot;2001:db8::/32&quot;,                         // IPv6 subnet<br>      &quot;fe80::/10&quot;,                             // Link-local range<br>      &quot;::1/128&quot;,                               // Localhost only<br>      &quot;2001:db8:85a3::/48&quot;,                    // Organization subnet<br>      <br>      // IPv6 Range (özel implementasyon gerektirir)<br>      &quot;2001:db8::1-2001:db8::100&quot;,<br>      <br>      // Özel durumlar<br>      &quot;0.0.0.0/0&quot;,             // Tüm IPv4 (dikkatli kullanın!)<br>      &quot;::/0&quot;                   // Tüm IPv6 (dikkatli kullanın!)<br>    ],<br>    <br>    &quot;Blacklist&quot;: [<br>      // Kötü amaçlı bilinen IP&#39;ler<br>      &quot;185.220.100.0/24&quot;,      // Tor exit nodes örneği<br>      &quot;198.96.155.0/24&quot;,       // Spam network örneği<br>      <br>      // Belirli ülke IP blokları (örnek)<br>      &quot;1.0.16.0/20&quot;,           // Çin bloğu örneği<br>      &quot;14.0.0.0/8&quot;,            // Çin bloğu örneği<br>      <br>      // IPv6 kötü amaçlı bloklar<br>      &quot;2001:4860::/32&quot;,        // Örnek blok<br>      <br>      // Tek IP&#39;ler<br>      &quot;203.0.113.1&quot;,           // Saldırgan IP<br>      &quot;192.0.2.100&quot;            // Test IP<br>    ],<br>    <br>    &quot;Settings&quot;: {<br>      &quot;EnableIPv6&quot;: true,<br>      &quot;EnableIPv4&quot;: true,<br>      &quot;LogBlockedRequests&quot;: true,<br>      &quot;BlockUnknownIPs&quot;: false,<br>      &quot;WhitelistOverridesBlacklist&quot;: true<br>    }<br>  }<br>}</pre><h3>Enhanced IP Filtering Implementation</h3><pre>public class AdvancedIPFilteringMiddleware<br>{<br>    private readonly RequestDelegate _next;<br>    private readonly IPFilteringOptions _options;<br>    private readonly ILogger&lt;AdvancedIPFilteringMiddleware&gt; _logger;<br>    <br>    public AdvancedIPFilteringMiddleware(<br>        RequestDelegate next,<br>        IOptions&lt;IPFilteringOptions&gt; options,<br>        ILogger&lt;AdvancedIPFilteringMiddleware&gt; logger)<br>    {<br>        _next = next;<br>        _options = options.Value;<br>        _logger = logger;<br>    }<br>    <br>    public async Task InvokeAsync(HttpContext context)<br>    {<br>        var clientIP = GetClientIPAddress(context);<br>        <br>        if (!IsIPAllowed(clientIP))<br>        {<br>            _logger.LogWarning(&quot;Access denied for IP: {IP} (Type: {Type})&quot;, <br>                clientIP, clientIP.AddressFamily);<br>            <br>            context.Response.StatusCode = 403;<br>            await context.Response.WriteAsync(&quot;Access denied&quot;);<br>            return;<br>        }<br>        <br>        await _next(context);<br>    }<br>    <br>    private IPAddress GetClientIPAddress(HttpContext context)<br>    {<br>        // X-Forwarded-For header&#39;ı kontrol et (proxy/load balancer için)<br>        var xForwardedFor = context.Request.Headers[&quot;X-Forwarded-For&quot;].FirstOrDefault();<br>        if (!string.IsNullOrEmpty(xForwardedFor))<br>        {<br>            var ips = xForwardedFor.Split(&#39;,&#39;, StringSplitOptions.RemoveEmptyEntries);<br>            foreach (var ip in ips)<br>            {<br>                if (IPAddress.TryParse(ip.Trim(), out var parsedIP))<br>                {<br>                    return parsedIP;<br>                }<br>            }<br>        }<br>        <br>        // X-Real-IP header&#39;ı kontrol et<br>        var xRealIP = context.Request.Headers[&quot;X-Real-IP&quot;].FirstOrDefault();<br>        if (!string.IsNullOrEmpty(xRealIP) &amp;&amp; IPAddress.TryParse(xRealIP, out var realIP))<br>        {<br>            return realIP;<br>        }<br>        <br>        // Cloudflare için<br>        var cfConnectingIP = context.Request.Headers[&quot;CF-Connecting-IP&quot;].FirstOrDefault();<br>        if (!string.IsNullOrEmpty(cfConnectingIP) &amp;&amp; IPAddress.TryParse(cfConnectingIP, out var cfIP))<br>        {<br>            return cfIP;<br>        }<br>        <br>        return context.Connection.RemoteIpAddress ?? IPAddress.None;<br>    }<br>    <br>    private bool IsIPAllowed(IPAddress clientIP)<br>    {<br>        // IPv4/IPv6 kontrolü<br>        if (!_options.Settings.EnableIPv4 &amp;&amp; clientIP.AddressFamily == AddressFamily.InterNetwork)<br>            return false;<br>        <br>        if (!_options.Settings.EnableIPv6 &amp;&amp; clientIP.AddressFamily == AddressFamily.InterNetworkV6)<br>            return false;<br>        <br>        // Whitelist kontrolü (öncelikli)<br>        if (_options.Whitelist?.Any() == true)<br>        {<br>            var isWhitelisted = _options.Whitelist.Any(rule =&gt; IsIPInRule(clientIP, rule));<br>            if (_options.Settings.WhitelistOverridesBlacklist &amp;&amp; isWhitelisted)<br>                return true;<br>            <br>            return isWhitelisted;<br>        }<br>        <br>        // Blacklist kontrolü<br>        if (_options.Blacklist?.Any() == true)<br>        {<br>            return !_options.Blacklist.Any(rule =&gt; IsIPInRule(clientIP, rule));<br>        }<br>        <br>        // Hiç kural yoksa default davranış<br>        return !_options.Settings.BlockUnknownIPs;<br>    }<br>    <br>    private bool IsIPInRule(IPAddress clientIP, string rule)<br>    {<br>        try<br>        {<br>            if (rule.Contains(&#39;/&#39;))<br>            {<br>                // CIDR notation<br>                return IsIPInCIDR(clientIP, rule);<br>            }<br>            else if (rule.Contains(&#39;-&#39;))<br>            {<br>                // Range notation<br>                return IsIPInRange(clientIP, rule);<br>            }<br>            else<br>            {<br>                // Single IP<br>                return IPAddress.TryParse(rule, out var ruleIP) &amp;&amp; clientIP.Equals(ruleIP);<br>            }<br>        }<br>        catch (Exception ex)<br>        {<br>            _logger.LogError(ex, &quot;Error parsing IP rule: {Rule}&quot;, rule);<br>            return false;<br>        }<br>    }<br>    <br>    private bool IsIPInCIDR(IPAddress clientIP, string cidr)<br>    {<br>        var parts = cidr.Split(&#39;/&#39;);<br>        if (parts.Length != 2 || !IPAddress.TryParse(parts[0], out var networkIP) || !int.TryParse(parts[1], out var prefixLength))<br>            return false;<br>        <br>        // IPv4 ve IPv6 uyumluluğu kontrol et<br>        if (clientIP.AddressFamily != networkIP.AddressFamily)<br>            return false;<br>        <br>        if (clientIP.AddressFamily == AddressFamily.InterNetwork)<br>        {<br>            return IsIPv4InCIDR(clientIP, networkIP, prefixLength);<br>        }<br>        else if (clientIP.AddressFamily == AddressFamily.InterNetworkV6)<br>        {<br>            return IsIPv6InCIDR(clientIP, networkIP, prefixLength);<br>        }<br>        <br>        return false;<br>    }<br>    <br>    private bool IsIPv4InCIDR(IPAddress clientIP, IPAddress networkIP, int prefixLength)<br>    {<br>        if (prefixLength &lt; 0 || prefixLength &gt; 32)<br>            return false;<br>        <br>        var clientBytes = clientIP.GetAddressBytes();<br>        var networkBytes = networkIP.GetAddressBytes();<br>        <br>        var bytesToCheck = prefixLength / 8;<br>        var bitsToCheck = prefixLength % 8;<br>        <br>        // Tam byte&#39;ları kontrol et<br>        for (int i = 0; i &lt; bytesToCheck; i++)<br>        {<br>            if (clientBytes[i] != networkBytes[i])<br>                return false;<br>        }<br>        <br>        // Kalan bitleri kontrol et<br>        if (bitsToCheck &gt; 0 &amp;&amp; bytesToCheck &lt; clientBytes.Length)<br>        {<br>            var mask = (byte)(0xFF &lt;&lt; (8 - bitsToCheck));<br>            if ((clientBytes[bytesToCheck] &amp; mask) != (networkBytes[bytesToCheck] &amp; mask))<br>                return false;<br>        }<br>        <br>        return true;<br>    }<br>    <br>    private bool IsIPv6InCIDR(IPAddress clientIP, IPAddress networkIP, int prefixLength)<br>    {<br>        if (prefixLength &lt; 0 || prefixLength &gt; 128)<br>            return false;<br>        <br>        var clientBytes = clientIP.GetAddressBytes();<br>        var networkBytes = networkIP.GetAddressBytes();<br>        <br>        var bytesToCheck = prefixLength / 8;<br>        var bitsToCheck = prefixLength % 8;<br>        <br>        // Tam byte&#39;ları kontrol et<br>        for (int i = 0; i &lt; bytesToCheck; i++)<br>        {<br>            if (clientBytes[i] != networkBytes[i])<br>                return false;<br>        }<br>        <br>        // Kalan bitleri kontrol et<br>        if (bitsToCheck &gt; 0 &amp;&amp; bytesToCheck &lt; clientBytes.Length)<br>        {<br>            var mask = (byte)(0xFF &lt;&lt; (8 - bitsToCheck));<br>            if ((clientBytes[bytesToCheck] &amp; mask) != (networkBytes[bytesToCheck] &amp; mask))<br>                return false;<br>        }<br>        <br>        return true;<br>    }<br>    <br>    private bool IsIPInRange(IPAddress clientIP, string range)<br>    {<br>        var parts = range.Split(&#39;-&#39;, StringSplitOptions.RemoveEmptyEntries);<br>        if (parts.Length != 2 || <br>            !IPAddress.TryParse(parts[0].Trim(), out var startIP) || <br>            !IPAddress.TryParse(parts[1].Trim(), out var endIP))<br>            return false;<br>        <br>        // Aynı IP family&#39;de olmalı<br>        if (clientIP.AddressFamily != startIP.AddressFamily || <br>            clientIP.AddressFamily != endIP.AddressFamily)<br>            return false;<br>        <br>        if (clientIP.AddressFamily == AddressFamily.InterNetwork)<br>        {<br>            return IsIPv4InRange(clientIP, startIP, endIP);<br>        }<br>        else if (clientIP.AddressFamily == AddressFamily.InterNetworkV6)<br>        {<br>            return IsIPv6InRange(clientIP, startIP, endIP);<br>        }<br>        <br>        return false;<br>    }<br>    <br>    private bool IsIPv4InRange(IPAddress clientIP, IPAddress startIP, IPAddress endIP)<br>    {<br>        var clientBytes = clientIP.GetAddressBytes();<br>        var startBytes = startIP.GetAddressBytes();<br>        var endBytes = endIP.GetAddressBytes();<br>        <br>        var clientInt = BitConverter.ToUInt32(clientBytes.Reverse().ToArray(), 0);<br>        var startInt = BitConverter.ToUInt32(startBytes.Reverse().ToArray(), 0);<br>        var endInt = BitConverter.ToUInt32(endBytes.Reverse().ToArray(), 0);<br>        <br>        return clientInt &gt;= startInt &amp;&amp; clientInt &lt;= endInt;<br>    }<br>    <br>    private bool IsIPv6InRange(IPAddress clientIP, IPAddress startIP, IPAddress endIP)<br>    {<br>        var clientBytes = clientIP.GetAddressBytes();<br>        var startBytes = startIP.GetAddressBytes();<br>        var endBytes = endIP.GetAddressBytes();<br>        <br>        // IPv6 için byte-by-byte karşılaştırma<br>        for (int i = 0; i &lt; 16; i++)<br>        {<br>            if (clientBytes[i] &lt; startBytes[i])<br>                return false;<br>            if (clientBytes[i] &gt; startBytes[i])<br>                break;<br>        }<br>        <br>        for (int i = 0; i &lt; 16; i++)<br>        {<br>            if (clientBytes[i] &gt; endBytes[i])<br>                return false;<br>            if (clientBytes[i] &lt; endBytes[i])<br>                break;<br>        }<br>        <br>        return true;<br>    }<br>}</pre><h3>Configuration Options Model</h3><pre>public class IPFilteringOptions<br>{<br>    public List&lt;string&gt; Whitelist { get; set; } = new();<br>    public List&lt;string&gt; Blacklist { get; set; } = new();<br>    public IPFilteringSettings Settings { get; set; } = new();<br>}</pre><pre>public class IPFilteringSettings<br>{<br>    public bool EnableIPv4 { get; set; } = true;<br>    public bool EnableIPv6 { get; set; } = true;<br>    public bool LogBlockedRequests { get; set; } = true;<br>    public bool BlockUnknownIPs { get; set; } = false;<br>    public bool WhitelistOverridesBlacklist { get; set; } = true;<br>}</pre><h3>IPv6 Özel Durumlar ve Notasyonlar</h3><pre>{<br>  &quot;IPFiltering&quot;: {<br>    &quot;IPv6Examples&quot;: {<br>      &quot;Comments&quot;: [<br>        &quot;IPv6 adresleri 128 bitlik ve 8 grup halinde yazılır&quot;,<br>        &quot;Her grup 4 hexadecimal karakter (16 bit)&quot;,<br>        &quot;Önde gelen sıfırlar atlanabilir&quot;,<br>        &quot;Ardışık sıfır grupları :: ile kısaltılabilir&quot;<br>      ],<br>      <br>      &quot;FullNotation&quot;: &quot;2001:0db8:85a3:0000:0000:8a2e:0370:7334&quot;,<br>      &quot;CompressedNotation&quot;: &quot;2001:db8:85a3::8a2e:370:7334&quot;,<br>      <br>      &quot;CommonRanges&quot;: [<br>        &quot;::1/128&quot;,           // Localhost<br>        &quot;fe80::/10&quot;,         // Link-local<br>        &quot;2001:db8::/32&quot;,     // Documentation<br>        &quot;fc00::/7&quot;,          // Unique local<br>        &quot;ff00::/8&quot;           // Multicast<br>      ],<br>      <br>      &quot;ProviderBlocks&quot;: [<br>        &quot;2001:4860::/32&quot;,    // Google<br>        &quot;2a03:2880::/32&quot;,    // Facebook<br>        &quot;2606:4700::/32&quot;     // Cloudflare<br>      ]<br>    }<br>  }<br>}</pre><h3>Gelişmiş Configuration</h3><pre>{<br>  &quot;IPFiltering&quot;: {<br>    &quot;Profiles&quot;: {<br>      &quot;Development&quot;: {<br>        &quot;Whitelist&quot;: [<br>          &quot;127.0.0.1&quot;,<br>          &quot;::1&quot;,<br>          &quot;192.168.0.0/16&quot;,<br>          &quot;10.0.0.0/8&quot;<br>        ],<br>        &quot;Settings&quot;: {<br>          &quot;EnableIPv6&quot;: true,<br>          &quot;BlockUnknownIPs&quot;: false<br>        }<br>      },<br>      <br>      &quot;Production&quot;: {<br>        &quot;Whitelist&quot;: [<br>          &quot;203.0.113.0/24&quot;,     // Office network<br>          &quot;198.51.100.0/24&quot;,    // Partner network<br>          &quot;2001:db8::/32&quot;       // Office IPv6<br>        ],<br>        &quot;Blacklist&quot;: [<br>          &quot;185.220.100.0/24&quot;,   // Known attackers<br>          &quot;192.0.2.0/24&quot;,       // Test network<br>          &quot;2001:db8:bad::/48&quot;   // Bad IPv6 range<br>        ],<br>        &quot;Settings&quot;: {<br>          &quot;BlockUnknownIPs&quot;: true,<br>          &quot;LogBlockedRequests&quot;: true<br>        }<br>      }<br>    },<br>    <br>    &quot;GeoBlocking&quot;: {<br>      &quot;BlockedCountries&quot;: [&quot;CN&quot;, &quot;RU&quot;, &quot;KP&quot;],<br>      &quot;AllowedCountries&quot;: [&quot;TR&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;GB&quot;]<br>    },<br>    <br>    &quot;SpecialRules&quot;: {<br>      &quot;AdminEndpoints&quot;: {<br>        &quot;Paths&quot;: [&quot;/api/admin/*&quot;, &quot;/api/system/*&quot;],<br>        &quot;Whitelist&quot;: [<br>          &quot;192.168.1.100&quot;,     // Admin workstation<br>          &quot;2001:db8::admin&quot;    // Admin IPv6<br>        ]<br>      },<br>      <br>      &quot;PublicAPI&quot;: {<br>        &quot;Paths&quot;: [&quot;/api/public/*&quot;],<br>        &quot;RateLimiting&quot;: {<br>          &quot;RequestsPerMinute&quot;: 100,<br>          &quot;BurstLimit&quot;: 20<br>        }<br>      }<br>    }<br>  }<br>}</pre><h3>Environment-based Configuration</h3><pre>// Program.cs<br>builder.Services.Configure&lt;IPFilteringOptions&gt;(options =&gt;<br>{<br>    var environment = builder.Environment.EnvironmentName;<br>    var section = builder.Configuration.GetSection($&quot;IPFiltering:Profiles:{environment}&quot;);<br>    <br>    if (section.Exists())<br>    {<br>        section.Bind(options);<br>    }<br>    else<br>    {<br>        // Fallback to default<br>        builder.Configuration.GetSection(&quot;IPFiltering&quot;).Bind(options);<br>    }<br>});</pre><h3>Validation ve Test</h3><pre>public class IPFilteringValidator<br>{<br>    public static List&lt;string&gt; ValidateConfiguration(IPFilteringOptions options)<br>    {<br>        var errors = new List&lt;string&gt;();<br>        <br>        // Whitelist validation<br>        foreach (var rule in options.Whitelist ?? new List&lt;string&gt;())<br>        {<br>            if (!IsValidIPRule(rule))<br>                errors.Add($&quot;Invalid whitelist rule: {rule}&quot;);<br>        }<br>        <br>        // Blacklist validation<br>        foreach (var rule in options.Blacklist ?? new List&lt;string&gt;())<br>        {<br>            if (!IsValidIPRule(rule))<br>                errors.Add($&quot;Invalid blacklist rule: {rule}&quot;);<br>        }<br>        <br>        return errors;<br>    }<br>    <br>    private static bool IsValidIPRule(string rule)<br>    {<br>        if (rule.Contains(&#39;/&#39;))<br>        {<br>            // CIDR validation<br>            var parts = rule.Split(&#39;/&#39;);<br>            return parts.Length == 2 &amp;&amp; <br>                   IPAddress.TryParse(parts[0], out var ip) &amp;&amp; <br>                   int.TryParse(parts[1], out var prefix) &amp;&amp;<br>                   IsValidPrefix(ip, prefix);<br>        }<br>        else if (rule.Contains(&#39;-&#39;))<br>        {<br>            // Range validation<br>            var parts = rule.Split(&#39;-&#39;);<br>            return parts.Length == 2 &amp;&amp; <br>                   IPAddress.TryParse(parts[0].Trim(), out _) &amp;&amp; <br>                   IPAddress.TryParse(parts[1].Trim(), out _);<br>        }<br>        else<br>        {<br>            // Single IP validation<br>            return IPAddress.TryParse(rule, out _);<br>        }<br>    }<br>    <br>    private static bool IsValidPrefix(IPAddress ip, int prefix)<br>    {<br>        return ip.AddressFamily switch<br>        {<br>            AddressFamily.InterNetwork =&gt; prefix &gt;= 0 &amp;&amp; prefix &lt;= 32,<br>            AddressFamily.InterNetworkV6 =&gt; prefix &gt;= 0 &amp;&amp; prefix &lt;= 128,<br>            _ =&gt; false<br>        };<br>    }<br>}</pre><p>Bu yapılandırma ile hem IPv4 hem IPv6 adreslerini etkili şekilde yönetebilir, farklı notasyonları destekleyebilir ve environment-specific kurallar tanımlayabilirsiniz.</p><p>Bu uygulamayı istersek tüm uygulamada istersekte Controller/method seviyesinde bu işlemi yapabiliriz.</p><h3>Uygulama seviyesi(Middleware seviyesi):</h3><p>appsettings.json düzenlemesi yapılır önce. şimdi bir class oluşturalım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*GpzeLEIC5n6wXof0NMPFCw.png" /><figcaption>class oluşturma</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*ZewAtAWksHwEADdZcTw_MQ.png" /><figcaption>Program.cs’ten verileri class yardımı ile çekme</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*Etmo3kT_GfbB6CHpVwnBcA.png" /><figcaption>IOptions&lt;IPList&gt; olarak çaığırmamızın sebebi apsettings’teki yapıyı IOptions interfacesi ile çağırabilmemizden kaynaklı. DI ile doldurmak için bu interface gerekiyor. Ayrıca middleware olabilmesi için RequestDelegate gerekmektedir gelen isteği aldı böylece.</figcaption></figure><p>Middleware tanımladığımız zaman gelen her istekte bu katmanlar çalışır. Invoke ile oluşturulan metotların amacı her gelen istekte çalışacak metotu belirlemek için kullanılır. Invoke veya InvokeAsync olarak kullanabiliriz. Tüm request ve responseler HttpContext aracılığı ile gerçekleşir. Bu sistem ile gelen her istek güvenlik açısından riskli mi değil mi bunu kontrol edebiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*6tCbq3uq0yizN4tiHuv5qw.png" /><figcaption>_next metotu gelen isteği bir sonraki katmana aktarır. ama whitelistte değilse 403 alarak return et ve ilerleme demektir diğer katmanlara geçmeden geri dönecektir.</figcaption></figure><h3>Controller/Method seviyesi:</h3><p>Filter ile yapabiliriz. Bir class ekleyelim CheckWhiteList class’ı olsun Filterlar sayesinde Controllerdaki metotlara istek gelmeden veya sonrasında yapılacak işlemleri belirleyebiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*YXbc_xhQJdZ5s-3OKL05tw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*-YPhTD3p34G8-aXFZ4Gs6w.png" /><figcaption>Devamı bunun anlamı işlemlerde sorun yoksa devam et demektir son satırdaki kodun anlamı.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*lCVninneDrtfOBmNODdFRA.png" /><figcaption>Program.cs eklemesi. Scoped yaptık her istek için bir tane oluşacak diye.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*r15HS-2O4Ac6u3CvFN2FNw.png" /><figcaption>Bu şekilde de kullanabiliriz böylece.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*I-BSAAnSjQjHoz7xwJi-BA.png" /><figcaption>Eğer Controller’ın başına eklersek bir Filter’i o Controller’ın tüm metotlarında geçerli olur bu sistem.</figcaption></figure><h3>SECRET PROTECTION</h3><p>secret manager tool(projede sağ tık ile görünüp aktif edilebilir.). Hassas bilgileri korunması. Connection string, token, Facebook, Google ClientSecret vs gibi canlıya yanlışlıkla deploy edilmemesi ezilmesi lazım. Ezmek için enviroment değişkenler tanımlamamız lazım. Bu tür verileri appsettings.json içerisinde tutuyoruz yanlışlıkla bunu githuba atmamak veya canlıya alırken yollamamak lazım deploy etmemek lazım. Bunun için Secret manager tool kullanacağız. Biz projemizi publish edersek eğer direkt olarak o zaman appsettings.json içerisindeki verileri görebiliriz. Eğer hassas bilgilerin varsa burda tutma Manager user secret içerisinde tut diyor. Connection string vs gibi bilgileri burada tut. Secret.json nerede peki? Tamamen ayrı bir yerde tutuluyor Ama ayağa kalkacağı zaman appsettings.json ile birleşiyor.</p><p>appsettings.json ana dosyamız gibi appsettings.Development Stagging gibi ayarlar ise appsettings’ten farklı olan yerler için kullanılır. appsettings.json hepsi için ortaktır. appsettings altındakiler appsettings.json içerisindeki ezerler. yani orada yapılan ayarlar çalışır eğer onlar kullanılıyorsa.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*KwZdcGMelfqIFQUbt2oDww.png" /><figcaption>secrets.json içerisinden okuruz bu verileri aslında sanki appsettings’ten gelmiş gibi davranır bu yapı ile bunun bize artısı publish ettiğimiz zaman bile buradaki verileri göremeyiz. Bilgisayarda başka bir yerde tutulur bunlar. Veriler proje dizininden ayrı bir yerde tutuluyor.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*CKpnmWKsTMsyXD8vaG68UQ.png" /><figcaption>Verilerin tutulduğu dosyanın adı buradadır. veriler bu dosyada şifrelenmeden tutuluyor buna dikkat etmemiz lazım.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*nzrCySys2NZPsYbLG0QiPw.png" /><figcaption>Bu yapı ile şunu yaptık, connection string verilerini apsettings.jsondan okuduk password’ü ise secrets.json içerisinden okuduk bu yapı ile.</figcaption></figure><p>Production ortamında secrets.json içerisindeki verileri environment ortamında atacağız docker olur aws olur vs. o environment değişkenler projedeki değerleri ezerler ve böylece gizli kalması gereken veriler gizli kalır. secrest.json içerisinde verileri nerede canlıya alacaksak orada belli etmemiz gizli bir biçimde tutmamız ve okunabilir bir halde kod yazmamız gerekir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*TkRYdls0q9Zb8maz-ubOLQ.png" /><figcaption>launchsettings.json içerisi.</figcaption></figure><p>Sadece devolopment sürümde ayağa kaldırma yaparsak eğer o zaman secrets.json ile appsettings.json birleşir Production’da ise birleşme olmaz secrets.json içerisindeki verileri environment olarak belirlememiz gerekir.</p><h3>CORS(CROSS SITE RESOURCE SHARING):</h3><p>CORS, web güvenliğinin temel taşlarından biri olan ve farklı origin’lerden (domain, protocol, port) gelen HTTP isteklerinin kontrollü şekilde işlenmesini sağlayan bir güvenlik politikasıdır.</p><h3>Same-Origin Policy ve CORS İhtiyacı</h3><p>Web browser’lar varsayılan olarak “Same-Origin Policy” uygular. Bu demektir ki:</p><pre>// Bu durumlar Same-Origin kabul edilir:<br>// https://myapp.com/api/users<br>// https://myapp.com/page.html</pre><pre>// Bu durumlar Cross-Origin kabul edilir:<br>// <a href="http://myapp.com/">http://myapp.com</a> → <a href="https://myapp.com/">https://myapp.com</a> (farklı protocol)<br>// <a href="https://myapp.com/">https://myapp.com</a> → <a href="https://api.myapp.com/">https://api.myapp.com</a> (farklı subdomain)<br>// <a href="https://myapp.com/">https://myapp.com</a> → <a href="https://myapp.com:8080/">https://myapp.com:8080</a> (farklı port)<br>// <a href="https://myapp.com/">https://myapp.com</a> → <a href="https://otherapp.com/">https://otherapp.com</a> (farklı domain)</pre><h3>CORS Nasıl Çalışır?</h3><h3>1. Simple Requests</h3><p>Basit istekler için browser doğrudan isteği gönderir:</p><pre>GET /api/users HTTP/1.1<br>Host: api.myapp.com<br>Origin: https://frontend.myapp.com</pre><pre>HTTP/1.1 200 OK<br>Access-Control-Allow-Origin: <a href="https://frontend.myapp.com/">https://frontend.myapp.com</a><br>Content-Type: application/json</pre><h3>2. Preflight Requests</h3><p>Karmaşık istekler için browser önce OPTIONS isteği gönderir:</p><pre>OPTIONS /api/users HTTP/1.1<br>Host: api.myapp.com<br>Origin: https://frontend.myapp.com<br>Access-Control-Request-Method: POST<br>Access-Control-Request-Headers: Content-Type, Authorization</pre><pre>HTTP/1.1 200 OK<br>Access-Control-Allow-Origin: <a href="https://frontend.myapp.com/">https://frontend.myapp.com</a><br>Access-Control-Allow-Methods: GET, POST, PUT, DELETE<br>Access-Control-Allow-Headers: Content-Type, Authorization<br>Access-Control-Max-Age: 3600</pre><h3>ASP.NET Core’da CORS Implementasyonu</h3><h3>1. Basit CORS Configuration</h3><pre>// Program.cs<br>var builder = WebApplication.CreateBuilder(args);</pre><pre>// CORS service&#39;i ekle<br>builder.Services.AddCors(options =&gt;<br>{<br>    options.AddDefaultPolicy(policy =&gt;<br>    {<br>        policy.AllowAnyOrigin()     // Tüm origin&#39;lere izin ver (GÜVENSİZ!)<br>              .AllowAnyMethod()     // Tüm HTTP method&#39;larına izin ver<br>              .AllowAnyHeader();    // Tüm header&#39;lara izin ver<br>    });<br>});</pre><pre>builder.Services.AddControllers();</pre><pre>var app = builder.Build();</pre><pre>// CORS middleware&#39;i ekle (önemli: UseRouting&#39;den önce)<br>app.UseCors();</pre><pre>app.UseRouting();<br>app.UseAuthentication();<br>app.UseAuthorization();<br>app.MapControllers();</pre><pre>app.Run();</pre><h3>2. Named Policy ile CORS</h3><pre>// Program.cs<br>builder.Services.AddCors(options =&gt;<br>{<br>    // Strict policy - production için önerilen<br>    options.AddPolicy(&quot;StrictPolicy&quot;, policy =&gt;<br>    {<br>        policy.WithOrigins(&quot;https://myapp.com&quot;, &quot;https://www.myapp.com&quot;)<br>              .WithMethods(&quot;GET&quot;, &quot;POST&quot;, &quot;PUT&quot;, &quot;DELETE&quot;)<br>              .WithHeaders(&quot;Content-Type&quot;, &quot;Authorization&quot;)<br>              .AllowCredentials(); // Cookie&#39;ler için gerekli<br>    });<br>    <br>    // Development policy - sadece geliştirme için<br>    options.AddPolicy(&quot;DevelopmentPolicy&quot;, policy =&gt;<br>    {<br>        policy.WithOrigins(&quot;http://localhost:3000&quot;, &quot;http://localhost:4200&quot;)<br>              .AllowAnyMethod()<br>              .AllowAnyHeader()<br>              .AllowCredentials();<br>    });<br>    <br>    // Public API policy<br>    options.AddPolicy(&quot;PublicAPIPolicy&quot;, policy =&gt;<br>    {<br>        policy.AllowAnyOrigin()<br>              .WithMethods(&quot;GET&quot;)<br>              .WithHeaders(&quot;Content-Type&quot;);<br>    });<br>});</pre><pre>var app = builder.Build();</pre><pre>// Environment&#39;a göre policy seçimi<br>if (app.Environment.IsDevelopment())<br>{<br>    app.UseCors(&quot;DevelopmentPolicy&quot;);<br>}<br>else<br>{<br>    app.UseCors(&quot;StrictPolicy&quot;);<br>}</pre><h3>3. Controller/Action Level CORS</h3><pre>[ApiController]<br>[Route(&quot;api/[controller]&quot;)]<br>[EnableCors(&quot;StrictPolicy&quot;)] // Controller seviyesinde CORS<br>public class UsersController : ControllerBase<br>{<br>    [HttpGet]<br>    public async Task&lt;IActionResult&gt; GetUsers()<br>    {<br>        return Ok();<br>    }<br>    <br>    [HttpPost]<br>    [EnableCors(&quot;PublicAPIPolicy&quot;)] // Action seviyesinde farklı policy<br>    public async Task&lt;IActionResult&gt; CreateUser([FromBody] CreateUserRequest request)<br>    {<br>        return Ok();<br>    }<br>    <br>    [HttpDelete(&quot;{id}&quot;)]<br>    [DisableCors] // Bu action için CORS&#39;u devre dışı bırak<br>    public async Task&lt;IActionResult&gt; DeleteUser(int id)<br>    {<br>        return Ok();<br>    }<br>}</pre><h3>Environment-based CORS Configuration</h3><pre>// appsettings.json<br>{<br>  &quot;CorsSettings&quot;: {<br>    &quot;AllowedOrigins&quot;: [<br>      &quot;https://myapp.com&quot;,<br>      &quot;https://www.myapp.com&quot;<br>    ],<br>    &quot;AllowedMethods&quot;: [&quot;GET&quot;, &quot;POST&quot;, &quot;PUT&quot;, &quot;DELETE&quot;],<br>    &quot;AllowedHeaders&quot;: [&quot;Content-Type&quot;, &quot;Authorization&quot;],<br>    &quot;AllowCredentials&quot;: true,<br>    &quot;MaxAge&quot;: 3600<br>  }<br>}</pre><pre>// appsettings.Development.json<br>{<br>  &quot;CorsSettings&quot;: {<br>    &quot;AllowedOrigins&quot;: [<br>      &quot;http://localhost:3000&quot;,<br>      &quot;http://localhost:4200&quot;,<br>      &quot;http://localhost:8080&quot;<br>    ],<br>    &quot;AllowedMethods&quot;: [&quot;*&quot;],<br>    &quot;AllowedHeaders&quot;: [&quot;*&quot;],<br>    &quot;AllowCredentials&quot;: true<br>  }<br>}</pre><pre>// Configuration model<br>public class CorsSettings<br>{<br>    public string[] AllowedOrigins { get; set; } = Array.Empty&lt;string&gt;();<br>    public string[] AllowedMethods { get; set; } = Array.Empty&lt;string&gt;();<br>    public string[] AllowedHeaders { get; set; } = Array.Empty&lt;string&gt;();<br>    public bool AllowCredentials { get; set; } = false;<br>    public int MaxAge { get; set; } = 0;<br>}</pre><pre>// Program.cs<br>var corsSettings = builder.Configuration.GetSection(&quot;CorsSettings&quot;).Get&lt;CorsSettings&gt;();</pre><pre>builder.Services.AddCors(options =&gt;<br>{<br>    options.AddDefaultPolicy(policy =&gt;<br>    {<br>        if (corsSettings.AllowedOrigins.Contains(&quot;*&quot;))<br>        {<br>            policy.AllowAnyOrigin();<br>        }<br>        else<br>        {<br>            policy.WithOrigins(corsSettings.AllowedOrigins);<br>        }<br>        <br>        if (corsSettings.AllowedMethods.Contains(&quot;*&quot;))<br>        {<br>            policy.AllowAnyMethod();<br>        }<br>        else<br>        {<br>            policy.WithMethods(corsSettings.AllowedMethods);<br>        }<br>        <br>        if (corsSettings.AllowedHeaders.Contains(&quot;*&quot;))<br>        {<br>            policy.AllowAnyHeader();<br>        }<br>        else<br>        {<br>            policy.WithHeaders(corsSettings.AllowedHeaders);<br>        }<br>        <br>        if (corsSettings.AllowCredentials)<br>        {<br>            policy.AllowCredentials();<br>        }<br>        <br>        if (corsSettings.MaxAge &gt; 0)<br>        {<br>            policy.SetPreflightMaxAge(TimeSpan.FromSeconds(corsSettings.MaxAge));<br>        }<br>    });<br>});</pre><h3>Dynamic CORS Policy</h3><pre>public class DynamicCorsService<br>{<br>    private readonly IConfiguration _configuration;<br>    private readonly ILogger&lt;DynamicCorsService&gt; _logger;<br>    <br>    public DynamicCorsService(IConfiguration configuration, ILogger&lt;DynamicCorsService&gt; logger)<br>    {<br>        _configuration = configuration;<br>        _logger = logger;<br>    }<br>    <br>    public bool IsOriginAllowed(string origin)<br>    {<br>        // Database&#39;den veya cache&#39;den allowed origins&#39;i al<br>        var allowedOrigins = GetAllowedOriginsFromDatabase();<br>        <br>        var isAllowed = allowedOrigins.Contains(origin, StringComparer.OrdinalIgnoreCase);<br>        <br>        _logger.LogInformation(&quot;CORS check for origin {Origin}: {IsAllowed}&quot;, origin, isAllowed);<br>        <br>        return isAllowed;<br>    }<br>    <br>    private List&lt;string&gt; GetAllowedOriginsFromDatabase()<br>    {<br>        // Bu method database&#39;den veya cache&#39;den origins&#39;i alabilir<br>        return new List&lt;string&gt;<br>        {<br>            &quot;https://myapp.com&quot;,<br>            &quot;https://www.myapp.com&quot;,<br>            &quot;https://admin.myapp.com&quot;<br>        };<br>    }<br>}</pre><pre>// Program.cs<br>builder.Services.AddSingleton&lt;DynamicCorsService&gt;();</pre><pre>builder.Services.AddCors(options =&gt;<br>{<br>    options.AddDefaultPolicy(policy =&gt;<br>    {<br>        policy.SetIsOriginAllowed(origin =&gt;<br>        {<br>            var corsService = builder.Services.BuildServiceProvider().GetService&lt;DynamicCorsService&gt;();<br>            return corsService?.IsOriginAllowed(origin) ?? false;<br>        })<br>        .AllowAnyMethod()<br>        .AllowAnyHeader()<br>        .AllowCredentials();<br>    });<br>});</pre><h3>CORS Debugging ve Monitoring</h3><pre>public class CorsLoggingMiddleware<br>{<br>    private readonly RequestDelegate _next;<br>    private readonly ILogger&lt;CorsLoggingMiddleware&gt; _logger;<br>    <br>    public CorsLoggingMiddleware(RequestDelegate next, ILogger&lt;CorsLoggingMiddleware&gt; logger)<br>    {<br>        _next = next;<br>        _logger = logger;<br>    }<br>    <br>    public async Task InvokeAsync(HttpContext context)<br>    {<br>        var origin = context.Request.Headers[&quot;Origin&quot;].FirstOrDefault();<br>        <br>        if (!string.IsNullOrEmpty(origin))<br>        {<br>            _logger.LogInformation(&quot;CORS request from origin: {Origin}&quot;, origin);<br>            <br>            // Preflight request kontrolü<br>            if (context.Request.Method == &quot;OPTIONS&quot;)<br>            {<br>                var requestMethod = context.Request.Headers[&quot;Access-Control-Request-Method&quot;].FirstOrDefault();<br>                var requestHeaders = context.Request.Headers[&quot;Access-Control-Request-Headers&quot;].FirstOrDefault();<br>                <br>                _logger.LogInformation(&quot;Preflight request - Method: {Method}, Headers: {Headers}&quot;, <br>                    requestMethod, requestHeaders);<br>            }<br>        }<br>        <br>        await _next(context);<br>        <br>        // Response headers&#39;ı logla<br>        if (!string.IsNullOrEmpty(origin))<br>        {<br>            var allowOrigin = context.Response.Headers[&quot;Access-Control-Allow-Origin&quot;].FirstOrDefault();<br>            var allowMethods = context.Response.Headers[&quot;Access-Control-Allow-Methods&quot;].FirstOrDefault();<br>            <br>            _logger.LogInformation(&quot;CORS response - Allow-Origin: {AllowOrigin}, Allow-Methods: {AllowMethods}&quot;, <br>                allowOrigin, allowMethods);<br>        }<br>    }<br>}</pre><pre>// Usage<br>app.UseMiddleware&lt;CorsLoggingMiddleware&gt;();<br>app.UseCors();</pre><h3>Frontend Integration Örnekleri</h3><h3>JavaScript/Fetch</h3><pre>// Simple request<br>fetch(&#39;https://api.myapp.com/users&#39;)<br>  .then(response =&gt; response.json())<br>  .then(data =&gt; console.log(data));</pre><pre>// Request with credentials<br>fetch(&#39;https://api.myapp.com/users&#39;, {<br>  method: &#39;POST&#39;,<br>  credentials: &#39;include&#39;, // Cookie&#39;leri gönder<br>  headers: {<br>    &#39;Content-Type&#39;: &#39;application/json&#39;,<br>    &#39;Authorization&#39;: &#39;Bearer &#39; + token<br>  },<br>  body: JSON.stringify({ name: &#39;John&#39; })<br>});</pre><pre>// CORS hatası yakalama<br>fetch(&#39;https://api.myapp.com/users&#39;)<br>  .catch(error =&gt; {<br>    if (error.name === &#39;TypeError&#39; &amp;&amp; error.message.includes(&#39;CORS&#39;)) {<br>      console.error(&#39;CORS error:&#39;, error);<br>    }<br>  });</pre><h3>Angular</h3><pre>// Angular HttpClient otomatik CORS handle eder<br>import { HttpClient } from &#39;@angular/common/http&#39;;</pre><pre>@Injectable()<br>export class UserService {<br>  constructor(private http: HttpClient) {}<br>  <br>  getUsers() {<br>    // CORS headers otomatik eklenir<br>    return this.http.get&lt;User[]&gt;(&#39;https://api.myapp.com/users&#39;);<br>  }<br>  <br>  createUser(user: User) {<br>    return this.http.post&lt;User&gt;(&#39;https://api.myapp.com/users&#39;, user, {<br>      withCredentials: true // Cookie&#39;ler için<br>    });<br>  }<br>}</pre><h3>React/Axios</h3><pre>import axios from &#39;axios&#39;;</pre><pre>// Axios instance with CORS configuration<br>const api = axios.create({<br>  baseURL: &#39;https://api.myapp.com&#39;,<br>  withCredentials: true, // Cookie&#39;ler için<br>  headers: {<br>    &#39;Content-Type&#39;: &#39;application/json&#39;<br>  }<br>});</pre><pre>// Request interceptor<br>api.interceptors.request.use(config =&gt; {<br>  const token = localStorage.getItem(&#39;token&#39;);<br>  if (token) {<br>    config.headers.Authorization = `Bearer ${token}`;<br>  }<br>  return config;<br>});</pre><pre>// Response interceptor for CORS errors<br>api.interceptors.response.use(<br>  response =&gt; response,<br>  error =&gt; {<br>    if (error.code === &#39;ERR_BLOCKED_BY_CORS&#39;) {<br>      console.error(&#39;CORS error detected&#39;);<br>    }<br>    return Promise.reject(error);<br>  }<br>);</pre><h3>Common CORS Errors ve Çözümler</h3><h3>1. “Access to fetch at ‘…’ has been blocked by CORS policy”</h3><pre>// Çözüm: Origin&#39;i CORS policy&#39;e ekle<br>builder.Services.AddCors(options =&gt;<br>{<br>    options.AddDefaultPolicy(policy =&gt;<br>    {<br>        policy.WithOrigins(&quot;http://localhost:3000&quot;) // Frontend URL&#39;ini ekle<br>              .AllowAnyMethod()<br>              .AllowAnyHeader();<br>    });<br>});</pre><h3>2. “Credential is not supported if the CORS header ‘Access-Control-Allow-Origin’ is ‘*’”</h3><pre>// Hatalı<br>policy.AllowAnyOrigin()<br>      .AllowCredentials(); // Bu kombinasyon çalışmaz!</pre><pre>// Doğru<br>policy.WithOrigins(&quot;https://myapp.com&quot;)<br>      .AllowCredentials();</pre><h3>3. “Method POST is not allowed by Access-Control-Allow-Methods”</h3><pre>// Çözüm: İhtiyaç duyulan method&#39;ları ekle<br>policy.WithMethods(&quot;GET&quot;, &quot;POST&quot;, &quot;PUT&quot;, &quot;DELETE&quot;);</pre><h3>Production Best Practices</h3><pre>// Production için güvenli CORS configuration<br>builder.Services.AddCors(options =&gt;<br>{<br>    options.AddDefaultPolicy(policy =&gt;<br>    {<br>        policy<br>            // Sadece bilinen domain&#39;lere izin ver<br>            .WithOrigins(<br>                &quot;https://myapp.com&quot;,<br>                &quot;https://www.myapp.com&quot;,<br>                &quot;https://admin.myapp.com&quot;<br>            )<br>            // Sadece gerekli method&#39;lara izin ver<br>            .WithMethods(&quot;GET&quot;, &quot;POST&quot;, &quot;PUT&quot;, &quot;DELETE&quot;)<br>            // Sadece gerekli header&#39;lara izin ver<br>            .WithHeaders(&quot;Content-Type&quot;, &quot;Authorization&quot;, &quot;X-Requested-With&quot;)<br>            // Credentials için gerekli<br>            .AllowCredentials()<br>            // Preflight cache süresi<br>            .SetPreflightMaxAge(TimeSpan.FromMinutes(10));<br>    });<br>});</pre><pre>// Security headers ile birlikte<br>app.Use(async (context, next) =&gt;<br>{<br>    context.Response.Headers.Add(&quot;X-Content-Type-Options&quot;, &quot;nosniff&quot;);<br>    context.Response.Headers.Add(&quot;X-Frame-Options&quot;, &quot;DENY&quot;);<br>    context.Response.Headers.Add(&quot;X-XSS-Protection&quot;, &quot;1; mode=block&quot;);<br>    await next();<br>});</pre><pre>app.UseCors();</pre><p>CORS, modern web uygulamalarında güvenlik ve fonksiyonellik arasındaki dengeyi sağlayan kritik bir mekanizmadır. Doğru yapılandırıldığında güvenliği artırır, yanlış yapılandırıldığında ciddi güvenlik açıklarına yol açabilir.</p><p>Cors’u hangi yazılımı kullanırsak kullanalım ayarlamamız gerekmektedir.</p><p>CORS, Cross-Origin Resource Sharing’in kısaltmasıdır ve web güvenliğinin temel mekanizmalarından biridir. Bir web sitesinin, farklı origin’den (domain, protokol veya port) gelen HTTP isteklerini kabul edip etmeyeceğini kontrol eden bir güvenlik politikasıdır.</p><h3>Same-Origin Policy ve CORS İhtiyacı</h3><p>Web browser’lar varsayılan olarak “Same-Origin Policy” adı verilen güvenlik kuralını uygular. Bu kural, bir web sayfasının sadece aynı origin’den kaynaklanan kaynaklara erişebileceğini belirtir. Origin, protocol + domain + port kombinasyonudur.</p><p>Örneğin:</p><ul><li><a href="https://myapp.com/">https://myapp.com</a> ve <a href="https://myapp.com/api">https://myapp.com/api</a> aynı origin</li><li><a href="https://myapp.com/">https://myapp.com</a> ve <a href="http://myapp.com/">http://myapp.com</a> farklı origin (protokol farkı)</li><li><a href="https://myapp.com/">https://myapp.com</a> ve <a href="https://api.myapp.com/">https://api.myapp.com</a> farklı origin (subdomain farkı)</li><li><a href="https://myapp.com/">https://myapp.com</a> ve <a href="https://myapp.com:8080/">https://myapp.com:8080</a> farklı origin (port farkı)</li></ul><p>Modern web uygulamalarında frontend ve backend genellikle farklı domain’lerde çalıştığı için Same-Origin Policy sorun yaratır. İşte bu noktada CORS devreye girer ve kontrollü bir şekilde cross-origin isteklere izin verir.</p><h3>CORS Nasıl Çalışır?</h3><p>CORS mekanizması iki türlü istek tipi ile çalışır:</p><h3>Basit İstekler (Simple Requests)</h3><p>Belirli kriterleri karşılayan istekler doğrudan gönderilir. Browser, isteği gönderir ve sunucunun response’unda CORS header’larını kontrol eder. Eğer sunucu o origin’e izin veriyorsa, response browser tarafından işlenir.</p><h3>Ön-Kontrol İstekleri (Preflight Requests)</h3><p>Daha karmaşık istekler için browser önce OPTIONS method’u ile bir ön-kontrol isteği gönderir. Bu istekte hangi method’ları ve header’ları kullanmak istediğini belirtir. Sunucu bu isteği onaylarsa, asıl istek gönderilir.</p><h3>CORS Header’ları</h3><h3>Response Headers (Sunucu → Browser)</h3><ul><li><strong>Access-Control-Allow-Origin</strong>: Hangi origin’lerin erişebileceğini belirtir</li><li><strong>Access-Control-Allow-Methods</strong>: İzin verilen HTTP method’ları</li><li><strong>Access-Control-Allow-Headers</strong>: İzin verilen request header’ları</li><li><strong>Access-Control-Allow-Credentials</strong>: Cookie ve authentication bilgilerinin gönderilip gönderilemeyeceği</li><li><strong>Access-Control-Max-Age</strong>: Preflight response’unun ne kadar süre cache’lenebileceği</li></ul><h3>Request Headers (Browser → Sunucu)</h3><ul><li><strong>Origin</strong>: İsteği gönderen origin</li><li><strong>Access-Control-Request-Method</strong>: Preflight’ta kullanılacak method</li><li><strong>Access-Control-Request-Headers</strong>: Preflight’ta kullanılacak header’lar</li></ul><h3>CORS’un Avantajları</h3><ol><li><strong>Güvenlik</strong>: Zararlı sitelerin API’nize yetkisiz erişimini engeller</li><li><strong>Kontrol</strong>: Hangi domain’lerin API’nize erişebileceğini tam olarak kontrol edebilirsiniz</li><li><strong>Esneklik</strong>: Farklı endpoint’ler için farklı CORS politikaları uygulayabilirsiniz</li><li><strong>Standart</strong>: W3C standardı olduğu için tüm modern browser’lar destekler</li></ol><h3>CORS’un Dezavantajları</h3><ol><li><strong>Komplekslik</strong>: Doğru yapılandırma teknik bilgi gerektirir</li><li><strong>Debug Zorluğu</strong>: CORS hataları bazen anlaşılması zor olabilir</li><li><strong>Performance</strong>: Preflight istekleri ek network trafiği yaratır</li><li><strong>Yanlış Yapılandırma Riski</strong>: Çok açık politikalar güvenlik açığı yaratabilir</li></ol><h3>ASP.NET Core’da CORS Konfigürasyonu</h3><p>ASP.NET Core’da CORS, middleware ve policy tabanlı olarak yapılandırılır. Temel olarak üç seviyede uygulanabilir:</p><ol><li><strong>Global Level</strong>: Tüm controller’lar için</li><li><strong>Controller Level</strong>: Belirli controller için</li><li><strong>Action Level</strong>: Belirli action method için</li></ol><h3>CORS Policy Türleri</h3><h3>Restrictive Policy (Önerilen — Production)</h3><p>Sadece bilinen ve güvenilir domain’lere izin verir. Specific origin’ler, method’lar ve header’lar belirtilir.</p><h3>Permissive Policy (Geliştirme)</h3><p>Geliştirme kolaylığı için daha esnek kurallar. Genellikle localhost adreslerine izin verir.</p><h3>Open Policy (Tehlikeli)</h3><p>Tüm origin’lere izin verir. Sadece public API’ler için kullanılmalı ve credential’lar desteklenmemeli.</p><h3>Environment-Based Configuration</h3><p>Farklı ortamlar için farklı CORS politikaları uygulamak yaygın bir praktiktir:</p><ul><li><strong>Development</strong>: Localhost adreslerine ve development URL’lerine izin</li><li><strong>Staging</strong>: Test ortamı URL’lerine izin</li><li><strong>Production</strong>: Sadece production domain’lerine izin</li></ul><h3>Common CORS Hataları</h3><ol><li><strong>Allow-Origin ile Credentials Çakışması</strong>: AllowAnyOrigin() ile AllowCredentials() birlikte kullanılamaz</li><li><strong>Method Not Allowed</strong>: İhtiyaç duyulan HTTP method CORS policy’de tanımlanmamış</li><li><strong>Header Not Allowed</strong>: Custom header’lar policy’de tanımlanmamış</li><li><strong>Preflight Failure</strong>: OPTIONS request’i doğru handle edilmiyor</li></ol><h3>Best Practices</h3><ol><li><strong>En Az Yetki Prensibi</strong>: Sadece gerekli origin, method ve header’lara izin verin</li><li><strong>Environment-Specific</strong>: Her ortam için uygun politika kullanın</li><li><strong>Credential Kontrolü</strong>: Sadece gerektiğinde credentials’a izin verin</li><li><strong>Monitoring</strong>: CORS isteklerini ve hatalarını loglayın</li><li><strong>Testing</strong>: Farklı browser’larda CORS davranışını test edin</li></ol><h3>Frontend Integration</h3><p>Frontend framework’ler (React, Angular, Vue) genellikle CORS’u otomatik handle eder, ancak:</p><ul><li><strong>Credentials</strong>: Cookie göndermek için withCredentials: true gerekli</li><li><strong>Custom Headers</strong>: Authorization header’ı için CORS policy’de tanım gerekli</li><li><strong>Error Handling</strong>: CORS hatalarını yakalamak ve kullanıcıya uygun mesaj göstermek</li></ul><h3>Security Considerations</h3><p>CORS bir güvenlik özelliği olsa da, yanlış yapılandırıldığında güvenlik açığı yaratabilir:</p><ul><li><strong>Wildcard Origin</strong>: Production’da * kullanmaktan kaçının</li><li><strong>Credential Exposure</strong>: Hassas API’ler için credential’ları kısıtlayın</li><li><strong>Header Validation</strong>: Custom header’ları validate edin</li><li><strong>HTTPS Only</strong>: Production’da sadece HTTPS origin’lere izin verin</li></ul><p>CORS, modern web development’in ayrılmaz bir parçasıdır ve doğru anlaşılıp uygulandığında hem güvenliği hem de functionality’yi sağlar. Ancak kompleks yapısı nedeniyle dikkatli yapılandırma gerektirir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*AOXnRol2RA8cDN7QXIBSPQ.png" /><figcaption>Browserlarda bir web sayfasına farklı bir domain ile istek gerçekleştirdiği zaman browserlar bunu reddeder. Bu davranışa Same-origin policy denir. protocol host port farklı ise reddeder mesela http:// ile https:// farklıdır onun için. Cors browserların same-origin policy’sini esnetmek amaçlı kullanılırlar. asp.net core api cors özelliği belirtirsek eğer hangi domainden gelen istekleri kabul edeceğiz bunu belirleyebiliriz. accsess control allow gönderir web api gelen domain ile aynı domaini göndererek. request bir origin gönderir hangi web sitesinden istek yaptığını belirtir.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*2JestVcZC-fc8YoPw_CVBg.png" /><figcaption>origin ile hangi sayfadan nereden istek yapıldığını belirleyebiliriz.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*3P0rpWMC1FzcweZo1vwCCg.png" /><figcaption>responsede ise access-control kısmında * var tarayıcı buna bakarak izin var diyebiliyor ve sistemi çalıştırabiliyor.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*tDJhN4gW6Upetsj5Kl-hog.png" /><figcaption>service cors eklemesi yaptık. her şeye izin verir şu anda policy kural tanımlamak gibi düşünülebilir.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/169/1*SeiNuB86n-WH7EmOxnZjng.png" /><figcaption>app. kısmına ekleme yaptık Routing’in altına Authorizationun üstüne ekledik. içerisini boş bırakırsak Cors()’un o zaman servisteki düzenlemeyi kullanacak.</figcaption></figure><h4>Sadece belli yerlerden gelen isteklere cevap verecek biçimde ayarlama yapma.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*9cdGLNEbXeH2peRa3EqanA.png" /><figcaption>Burada yeni bir kural tanımladık bu kural ile beraber sadece buradan gelen isteklere cevap verecek biçimde ayarlama yaptık.</figcaption></figure><p>cors ile reddetme yapamayız tarayıcının politikasını yumuşatabiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*AXgj7da-I-vjT7eUfVuqKg.png" /><figcaption>Burada AllowSite2 ile mysite2den gelen isteklerin hepsini değil headerında belli bir parametreyi taşıyan istekleri kabul eder biçime getireceğiz.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/185/1*9CIIAglhalLfEwSAUpB7kg.png" /><figcaption>Burada AllowSites2 yazarak middlewarede hangi kuralın çalışacağını belirleyebiliriz.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*seINXAD46LCQE2KbolBWAA.png" /><figcaption>tüm subdomainleri kabul et diyebiliriz burada. herhangi bir headera herhangi bir metota izin ver diyebiliriz.</figcaption></figure><h4>Controller ve method bazında cors:</h4><p>bir Controller bir Policy başka Controller diğer Policy’i kullansın istersek eğer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*vd8qxt-V8wb29e1x4HobVw.png" /><figcaption>önce yapılandırmamızı yaparız. iki tane kural belirledik. app.UseCors()’un içini boşalttık böylece Controllerlarda belirteceğiz hangi Policy’i kullanacağımızı.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*_8N4y6fSq3laH7ND1bZc6Q.png" /><figcaption>Böylece AllowSites2 Policy’sini method seviyesinde kullanabilir olduk. Gelen istekleri kabul ettirebilir olduk böylece.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*kbZNUBOoBLSvWgzPBcZLwA.png" /><figcaption>Controller seviyesinde uygulamak için ise Attribute’yi görüldüğü gibi eklememiz gerekmektedir.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*jvOkHpiVhkNiC_86XkDOfQ.png" /><figcaption>Controller seviyesinde uyguladıktan sonra bazı metotları bundan ayrı tutmak istersek [DisableCors kullanırız]</figcaption></figure><h3>GENEL GÜVENLİK AÇIKLARI VE KORUNMA YOLLARI:</h3><h3>XSS(CROSS SITE SCRIPTING):</h3><p>Server tarafında değil Client tarafında yapılan bir script saldırısıdır. HTML, js gibi dillerin güvenlik zaafiyetlerinden ortaya çıkmaktadır kullanıcının bilgileri session, cookie gibi yerlerden bilgilerin çalınmasıdır. Saldırılan uygulama değil kullanıcıdır. Kullanıcının bilgileri alınır. Web tabanlı bir saldırıdır. Sitenin görünümünü değiştirebilir. Bir script girip siteye o zaman sistemi bozabilir. Hacker bir js kodunu siteye enjekte eder cookie gibi bilgileri çalmak için kullanıcının tarayıcısında bu script çalışır ve bilgileri hackera gönderir. gelen bilgileri validation etmemiz gerekir. Reflected XSS ve Stored XSS gibi türleri vardır. Mesela ekrana veri girilen bir alana kötü niyetli bir scripti girerek bu saldırıyı gerçekleştirebilir. websitemizde form elemanları kullandığımız ve validasyon yapmadığımız zaman gerçekleşir genel olarak.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*figZMTZM_hhdejYakmYqWw.png" /></figure><h4>Reflected XSS:</h4><p>Anlık olarak yapılan bir saldırıdır. En az hasar veren xss’tir. Kimin oturumu açıksa onu etkiler sadece o anda açık olanları. Encode ederek gelen verileri bunun önüne geçebiliriz. veri gösterirken decode ederek zararlı yazılımı zararsız hale getirebiliriz. ViewBag yerine Html.Raw kullanırsak buna maruz kalabiliriz mvc projelerinde.</p><p><strong>Reflected XSS (Cross-Site Scripting)</strong>, kullanıcıdan gelen zararlı scriptlerin sunucu tarafından filtrelenmeden geri döndürülüp browser’da çalıştırılması saldırısıdır. ASP.NET Web API’de buna karşı çok katmanlı savunma stratejisi uygulamalısınız:</p><p><strong>1. Input Validation (Giriş Doğrulama):</strong></p><pre>public class BookSearchParameters<br>{<br>    [StringLength(100, MinimumLength = 1)]<br>    [RegularExpression(@&quot;^[a-zA-Z0-9\s\-_]+$&quot;, <br>        ErrorMessage = &quot;Search term contains invalid characters&quot;)]<br>    public string? SearchTerm { get; set; }<br>}<br>// Controller&#39;da<br>[HttpGet]<br>public IActionResult Search([FromQuery] BookSearchParameters parameters)<br>{<br>    if (!ModelState.IsValid)<br>        return BadRequest(ModelState);<br>    <br>    // Ekstra sanitization<br>    var sanitized = Regex.Replace(parameters.SearchTerm ?? &quot;&quot;, @&quot;[&lt;&gt;&quot;&quot;&#39;/]&quot;, &quot;&quot;);<br>    <br>    // Arama işlemi...<br>}</pre><p><strong>2. Output Encoding (Otomatik — ASP.NET Core Default):</strong> ASP.NET Core, JSON serialization sırasında otomatik olarak HTML encoding yapar, ancak dikkat edilmesi gereken durumlar:</p><pre>// GÜVENLİ - JSON otomatik encode eder<br>return Ok(new { SearchTerm = userInput, Results = books });<br>// TEHLİKELİ - Raw HTML döndürme<br>return Content($&quot;&lt;div&gt;Results for: {userInput}&lt;/div&gt;&quot;, &quot;text/html&quot;); // YAPMAYIN!<br>// GÜVENLİ - Manuel encoding ile<br>return Content($&quot;&lt;div&gt;Results for: {HtmlEncoder.Default.Encode(userInput)}&lt;/div&gt;&quot;, &quot;text/html&quot;);</pre><p><strong>3. Content Security Policy (CSP) Headers:</strong></p><pre>// Program.cs veya Startup.cs<br>app.Use(async (context, next) =&gt;<br>{<br>    context.Response.Headers.Add(&quot;Content-Security-Policy&quot;, <br>        &quot;default-src &#39;self&#39;; script-src &#39;self&#39;; object-src &#39;none&#39;&quot;);<br>    context.Response.Headers.Add(&quot;X-Content-Type-Options&quot;, &quot;nosniff&quot;);<br>    context.Response.Headers.Add(&quot;X-Frame-Options&quot;, &quot;DENY&quot;);<br>    context.Response.Headers.Add(&quot;X-XSS-Protection&quot;, &quot;1; mode=block&quot;);<br>    await next();<br>});<br><br>// Veya middleware ile<br>public class SecurityHeadersMiddleware<br>{<br>    private readonly RequestDelegate _next;<br>    public SecurityHeadersMiddleware(RequestDelegate next)<br>    {<br>        _next = next;<br>    }<br>    public async Task InvokeAsync(HttpContext context)<br>    {<br>        context.Response.Headers.Add(&quot;Content-Security-Policy&quot;, <br>            &quot;default-src &#39;self&#39;; script-src &#39;self&#39; &#39;unsafe-inline&#39; &#39;unsafe-eval&#39;; style-src &#39;self&#39; &#39;unsafe-inline&#39;&quot;);<br>        context.Response.Headers.Add(&quot;X-Content-Type-Options&quot;, &quot;nosniff&quot;);<br>        context.Response.Headers.Add(&quot;Referrer-Policy&quot;, &quot;strict-origin-when-cross-origin&quot;);<br>        <br>        await _next(context);<br>    }<br>}<br>// Program.cs&#39;de<br>app.UseMiddleware&lt;SecurityHeadersMiddleware&gt;();</pre><p><strong>4. AntiXSS Kütüphanesi Kullanımı:</strong></p><pre>// Microsoft.Security.Application.AntiXssEncoder (eski ama hala kullanılabilir)<br>// veya HtmlSanitizer paketi (daha modern)<br>using Ganss.Xss;<br>public class SanitizationService<br>{<br>    private readonly HtmlSanitizer _sanitizer;<br>    <br>    public SanitizationService()<br>    {<br>        _sanitizer = new HtmlSanitizer();<br>        _sanitizer.AllowedTags.Clear(); // Hiçbir HTML tag&#39;ine izin verme<br>        // Veya<br>        _sanitizer.AllowedTags.Add(&quot;b&quot;);<br>        _sanitizer.AllowedTags.Add(&quot;i&quot;);<br>        _sanitizer.AllowedTags.Add(&quot;u&quot;);<br>    }<br>    <br>    public string Sanitize(string input)<br>    {<br>        if (string.IsNullOrEmpty(input))<br>            return input;<br>            <br>        return _sanitizer.Sanitize(input);<br>    }<br>}<br>// Controller&#39;da<br>[HttpPost]<br>public IActionResult CreateBook([FromBody] BookDto bookDto)<br>{<br>    bookDto.Title = _sanitizationService.Sanitize(bookDto.Title);<br>    bookDto.Description = _sanitizationService.Sanitize(bookDto.Description);<br>    <br>    // Kaydetme işlemi...<br>}</pre><p><strong>5. FluentValidation ile Güvenli Validation:</strong></p><pre>public class BookSearchParametersValidator : AbstractValidator&lt;BookSearchParameters&gt;<br>{<br>    public BookSearchParametersValidator()<br>    {<br>        RuleFor(x =&gt; x.SearchTerm)<br>            .MaximumLength(100)<br>            .Must(BeValidSearchTerm)<br>            .WithMessage(&quot;Search term contains potentially dangerous characters&quot;);<br>    }<br>    <br>    private bool BeValidSearchTerm(string? searchTerm)<br>    {<br>        if (string.IsNullOrEmpty(searchTerm))<br>            return true;<br>            <br>        // Script tag&#39;leri, event handler&#39;ları kontrol et<br>        var dangerousPatterns = new[]<br>        {<br>            &quot;&lt;script&quot;, &quot;javascript:&quot;, &quot;onerror=&quot;, &quot;onload=&quot;, <br>            &quot;&lt;iframe&quot;, &quot;eval(&quot;, &quot;expression(&quot;<br>        };<br>        <br>        return !dangerousPatterns.Any(pattern =&gt; <br>            searchTerm.Contains(pattern, StringComparison.OrdinalIgnoreCase));<br>    }<br>}</pre><p><strong>6. API’nin Response Type’ını Belirle:</strong></p><pre>[ApiController]<br>[Route(&quot;api/[controller]&quot;)]<br>[Produces(&quot;application/json&quot;)] // Sadece JSON döndür<br>public class BooksController : ControllerBase<br>{<br>    [HttpGet]<br>    public IActionResult GetBooks([FromQuery] string searchTerm)<br>    {<br>        // Browser JSON&#39;ı HTML olarak çalıştıramaz<br>        return Ok(new { SearchTerm = searchTerm, Results = books });<br>    }<br>}</pre><p><strong>7. CORS Konfigürasyonu:</strong></p><pre>// Program.cs<br>builder.Services.AddCors(options =&gt;<br>{<br>    options.AddPolicy(&quot;ApiPolicy&quot;, builder =&gt;<br>    {<br>        builder.WithOrigins(&quot;https://trustedsite.com&quot;)<br>               .AllowAnyMethod()<br>               .AllowAnyHeader()<br>               .AllowCredentials();<br>    });<br>});<br>app.UseCors(&quot;ApiPolicy&quot;);</pre><p><strong>8. Request Size Limitleri:</strong></p><pre>builder.Services.Configure&lt;FormOptions&gt;(options =&gt;<br>{<br>    options.ValueLengthLimit = 1024; // 1KB<br>    options.MultipartBodyLengthLimit = 10485760; // 10MB<br>});<br>// Controller seviyesinde<br>[RequestSizeLimit(1024)]<br>[HttpPost]<br>public IActionResult CreateBook([FromBody] BookDto bookDto)<br>{<br>    // ...<br>}</pre><p><strong>9. Rate Limiting (Abuse Prevention):</strong></p><pre>// AspNetCoreRateLimit paketi ile<br>builder.Services.AddMemoryCache();<br>builder.Services.Configure&lt;IpRateLimitOptions&gt;(options =&gt;<br>{<br>    options.GeneralRules = new List&lt;RateLimitRule&gt;<br>    {<br>        new RateLimitRule<br>        {<br>            Endpoint = &quot;*&quot;,<br>            Limit = 100,<br>            Period = &quot;1m&quot;<br>        }<br>    };<br>});</pre><p><strong>10. Logging ve Monitoring:</strong></p><pre>public class XssDetectionMiddleware<br>{<br>    private readonly RequestDelegate _next;<br>    private readonly ILogger&lt;XssDetectionMiddleware&gt; _logger;<br>public async Task InvokeAsync(HttpContext context)<br>    {<br>        var queryString = context.Request.QueryString.ToString();<br>        <br>        if (ContainsPotentialXss(queryString))<br>        {<br>            _logger.LogWarning(<br>                &quot;Potential XSS attempt detected from IP: {IP}, Query: {Query}&quot;,<br>                context.Connection.RemoteIpAddress,<br>                queryString);<br>                <br>            context.Response.StatusCode = 400;<br>            await context.Response.WriteAsync(&quot;Invalid request&quot;);<br>            return;<br>        }<br>        <br>        await _next(context);<br>    }<br>    <br>    private bool ContainsPotentialXss(string input)<br>    {<br>        var xssPatterns = new[] { &quot;&lt;script&quot;, &quot;javascript:&quot;, &quot;onerror=&quot; };<br>        return xssPatterns.Any(p =&gt; input.Contains(p, StringComparison.OrdinalIgnoreCase));<br>    }<br>}</pre><p><strong>Kritik Noktalar:</strong></p><ul><li><strong>Asla kullanıcı girdisine güvenmeyin</strong> — her zaman validate ve sanitize edin</li><li><strong>Defense in Depth:</strong> Tek bir önlem yeterli değil, katmanlı savunma yapın</li><li><strong>JSON API’lerde risk düşük:</strong> Web API genelde JSON döndürdüğü için reflected XSS riski daha azdır, ancak yine de dikkatli olun</li><li><strong>HTML döndürmeyin:</strong> Eğer HTML döndürmeniz gerekiyorsa mutlaka encode edin</li><li><strong>Third-party kütüphaneler:</strong> DOMPurify (client-side), HtmlSanitizer (server-side) gibi test edilmiş araçlar kullanın</li><li><strong>Penetration testing:</strong> Düzenli güvenlik testleri yapın veya yaptırın</li></ul><p>Bu önlemler birlikte uygulandığında ASP.NET Web API’niz reflected XSS saldırılarına karşı oldukça güvenli hale gelir.</p><h4>Stored XSS:</h4><p>script kodunun veritabanı veya dosyaya entegre edilmesidir. Milyonlarca kişinin verileri çalınabilir. Veritabanı veya dosyadaki veriyi okumaya çalıştığımızda ilgili script çalışıcak ve oturum bilgileri çalınacak.</p><p><strong>Stored XSS (Persistent XSS)</strong>, kullanıcıdan gelen zararlı scriptlerin veritabanına kaydedilip daha sonra başka kullanıcılara gösterildiğinde çalışması saldırısıdır ve <strong>Reflected XSS’den çok daha tehlikelidir</strong> çünkü kalıcıdır ve tüm kullanıcıları etkileyebilir. ASP.NET Web API’de kapsamlı önlemler şunlardır:</p><p><strong>1. Input Sanitization — Veri Kaydedilmeden Önce Temizleme:</strong></p><pre>// HtmlSanitizer NuGet paketi<br>using Ganss.Xss;<br>public class SanitizationService : ISanitizationService<br>{<br>    private readonly HtmlSanitizer _sanitizer;<br>    <br>    public SanitizationService()<br>    {<br>        _sanitizer = new HtmlSanitizer();<br>        <br>        // Strikt mod - HİÇBİR HTML tag&#39;ine izin verme<br>        _sanitizer.AllowedTags.Clear();<br>        _sanitizer.AllowedAttributes.Clear();<br>        <br>        // Veya sadece güvenli tag&#39;lere izin ver<br>        _sanitizer.AllowedTags.Add(&quot;b&quot;);<br>        _sanitizer.AllowedTags.Add(&quot;i&quot;);<br>        _sanitizer.AllowedTags.Add(&quot;u&quot;);<br>        _sanitizer.AllowedTags.Add(&quot;p&quot;);<br>        _sanitizer.AllowedTags.Add(&quot;br&quot;);<br>        <br>        // Tehlikeli attribute&#39;ları engelle<br>        _sanitizer.AllowedAttributes.Add(&quot;href&quot;);<br>        _sanitizer.AllowedSchemes.Add(&quot;http&quot;);<br>        _sanitizer.AllowedSchemes.Add(&quot;https&quot;);<br>        // javascript:, data:, vbscript: gibi scheme&#39;leri engelle<br>    }<br>    <br>    public string Sanitize(string input)<br>    {<br>        if (string.IsNullOrEmpty(input))<br>            return input;<br>            <br>        return _sanitizer.Sanitize(input);<br>    }<br>    <br>    public string StrictSanitize(string input)<br>    {<br>        if (string.IsNullOrEmpty(input))<br>            return input;<br>        <br>        // Tüm HTML&#39;i strip et<br>        return Regex.Replace(input, @&quot;&lt;[^&gt;]*&gt;&quot;, string.Empty);<br>    }<br>}<br>// Application Layer - Handler&#39;da kullanım<br>public class CreateBookCommandHandler : IRequestHandler&lt;CreateBookCommand, BookDto&gt;<br>{<br>    private readonly ISanitizationService _sanitizer;<br>    private readonly IBookRepository _repository;<br>    <br>    public async Task&lt;BookDto&gt; Handle(CreateBookCommand request, CancellationToken ct)<br>    {<br>        var book = new Book<br>        {<br>            Title = _sanitizer.StrictSanitize(request.Title),<br>            Author = _sanitizer.StrictSanitize(request.Author),<br>            Description = _sanitizer.Sanitize(request.Description), // Bazı HTML&#39;e izin ver<br>            ISBN = _sanitizer.StrictSanitize(request.ISBN)<br>        };<br>        <br>        await _repository.AddAsync(book);<br>        return _mapper.Map&lt;BookDto&gt;(book);<br>    }<br>}</pre><p><strong>2. Validation Katmanında Kontrol:</strong></p><pre>public class CreateBookCommandValidator : AbstractValidator&lt;CreateBookCommand&gt;<br>{<br>    public CreateBookCommandValidator()<br>    {<br>        RuleFor(x =&gt; x.Title)<br>            .NotEmpty()<br>            .MaximumLength(200)<br>            .Must(NotContainDangerousContent)<br>            .WithMessage(&quot;Title contains potentially dangerous content&quot;);<br>            <br>        RuleFor(x =&gt; x.Description)<br>            .MaximumLength(5000)<br>            .Must(NotContainDangerousScripts)<br>            .WithMessage(&quot;Description contains potentially dangerous scripts&quot;);<br>    }<br>    <br>    private bool NotContainDangerousContent(string value)<br>    {<br>        if (string.IsNullOrEmpty(value))<br>            return true;<br>            <br>        var dangerousPatterns = new[]<br>        {<br>            &quot;&lt;script&quot;, &quot;&lt;/script&gt;&quot;, &quot;javascript:&quot;, &quot;onerror=&quot;, &quot;onload=&quot;,<br>            &quot;onclick=&quot;, &quot;onmouseover=&quot;, &quot;&lt;iframe&quot;, &quot;eval(&quot;, &quot;expression(&quot;,<br>            &quot;vbscript:&quot;, &quot;data:text/html&quot;, &quot;&lt;object&quot;, &quot;&lt;embed&quot;, <br>            &quot;document.cookie&quot;, &quot;document.write&quot;, &quot;&lt;svg/onload&quot;<br>        };<br>        <br>        return !dangerousPatterns.Any(pattern =&gt; <br>            value.Contains(pattern, StringComparison.OrdinalIgnoreCase));<br>    }<br>    <br>    private bool NotContainDangerousScripts(string value)<br>    {<br>        if (string.IsNullOrEmpty(value))<br>            return true;<br>        <br>        // HTML tag&#39;lerini kontrol et ancak zararsız olanları kabul et<br>        var scriptPattern = @&quot;&lt;script[\s\S]*?&gt;[\s\S]*?&lt;/script&gt;&quot;;<br>        var eventHandlerPattern = @&quot;\bon\w+\s*=&quot;;<br>        var javascriptPattern = @&quot;javascript:&quot;;<br>        <br>        return !Regex.IsMatch(value, scriptPattern, RegexOptions.IgnoreCase) &amp;&amp;<br>               !Regex.IsMatch(value, eventHandlerPattern, RegexOptions.IgnoreCase) &amp;&amp;<br>               !value.Contains(javascriptPattern, StringComparison.OrdinalIgnoreCase);<br>    }<br>}</pre><p><strong>3. Entity Seviyesinde Sanitization (Domain Events ile):</strong></p><pre>public class Book : BaseEntity<br>{<br>    private string _title;<br>    private string _description;<br>    <br>    public string Title <br>    { <br>        get =&gt; _title;<br>        set =&gt; _title = SanitizeInput(value);<br>    }<br>    <br>    public string Description<br>    {<br>        get =&gt; _description;<br>        set =&gt; _description = SanitizeInput(value);<br>    }<br>    <br>    private string SanitizeInput(string input)<br>    {<br>        if (string.IsNullOrEmpty(input))<br>            return input;<br>            <br>        // Temel sanitization - iş kuralına göre özelleştir<br>        return Regex.Replace(input, @&quot;&lt;script[\s\S]*?&gt;[\s\S]*?&lt;/script&gt;&quot;, <br>            string.Empty, RegexOptions.IgnoreCase);<br>    }<br>}</pre><p><strong>4. Output Encoding — Veri Okunurken Encode Etme:</strong></p><pre>// API Response&#39;da otomatik encoding<br>[ApiController]<br>[Route(&quot;api/[controller]&quot;)]<br>public class BooksController : ControllerBase<br>{<br>    [HttpGet(&quot;{id}&quot;)]<br>    public async Task&lt;IActionResult&gt; GetBook(int id)<br>    {<br>        var book = await _mediator.Send(new GetBookQuery { Id = id });<br>        <br>        // JSON serializer otomatik encode eder<br>        // Ancak ekstra güvenlik için DTO&#39;da da encode edebilirsiniz<br>        return Ok(book); // Güvenli - JSON otomatik encode eder<br>    }<br>}<br>// Eğer HTML döndürmek zorundasanız<br>public class BookDto<br>{<br>    private readonly IHtmlEncoder _encoder;<br>    <br>    public string Title { get; set; }<br>    public string Description { get; set; }<br>    <br>    public string GetEncodedTitle()<br>    {<br>        return HtmlEncoder.Default.Encode(Title);<br>    }<br>    <br>    public string GetEncodedDescription()<br>    {<br>        return HtmlEncoder.Default.Encode(Description);<br>    }<br>}</pre><p><strong>5. Content Security Policy (CSP) — Frontend için:</strong></p><pre>// Program.cs<br>app.Use(async (context, next) =&gt;<br>{<br>    // Strict CSP policy<br>    context.Response.Headers.Add(&quot;Content-Security-Policy&quot;, <br>        &quot;default-src &#39;self&#39;; &quot; +<br>        &quot;script-src &#39;self&#39;; &quot; +  // Sadece kendi domain&#39;inizden script<br>        &quot;style-src &#39;self&#39; &#39;unsafe-inline&#39;; &quot; +<br>        &quot;img-src &#39;self&#39; data: https:; &quot; +<br>        &quot;font-src &#39;self&#39;; &quot; +<br>        &quot;connect-src &#39;self&#39;; &quot; +<br>        &quot;frame-ancestors &#39;none&#39;; &quot; +<br>        &quot;base-uri &#39;self&#39;; &quot; +<br>        &quot;form-action &#39;self&#39;&quot;);<br>    <br>    // Diğer güvenlik header&#39;ları<br>    context.Response.Headers.Add(&quot;X-Content-Type-Options&quot;, &quot;nosniff&quot;);<br>    context.Response.Headers.Add(&quot;X-Frame-Options&quot;, &quot;DENY&quot;);<br>    context.Response.Headers.Add(&quot;X-XSS-Protection&quot;, &quot;1; mode=block&quot;);<br>    context.Response.Headers.Add(&quot;Referrer-Policy&quot;, &quot;strict-origin-when-cross-origin&quot;);<br>    context.Response.Headers.Add(&quot;Permissions-Policy&quot;, &quot;geolocation=(), microphone=(), camera=()&quot;);<br>    <br>    await next();<br>});</pre><p><strong>6. Database Seviyesinde Constraint’ler:</strong></p><pre>// Entity Framework Configuration<br>public class BookConfiguration : IEntityTypeConfiguration&lt;Book&gt;<br>{<br>    public void Configure(EntityTypeBuilder&lt;Book&gt; builder)<br>    {<br>        builder.Property(b =&gt; b.Title)<br>            .IsRequired()<br>            .HasMaxLength(200);<br>            <br>        builder.Property(b =&gt; b.Description)<br>            .HasMaxLength(5000);<br>            <br>        // SQL Injection&#39;a karşı da koruma<br>        builder.ToTable(tb =&gt; tb.HasCheckConstraint(<br>            &quot;CK_Book_NoScriptTags&quot;, <br>            &quot;[Title] NOT LIKE &#39;%&lt;script%&#39; AND [Description] NOT LIKE &#39;%&lt;script%&#39;&quot;));<br>    }<br>}</pre><p><strong>7. Middleware ile Global Sanitization:</strong></p><pre>public class XssSanitizationMiddleware<br>{<br>    private readonly RequestDelegate _next;<br>    private readonly ILogger&lt;XssSanitizationMiddleware&gt; _logger;<br>    private readonly HtmlSanitizer _sanitizer;<br>    <br>    public XssSanitizationMiddleware(RequestDelegate next, ILogger&lt;XssSanitizationMiddleware&gt; logger)<br>    {<br>        _next = next;<br>        _logger = logger;<br>        _sanitizer = new HtmlSanitizer();<br>        _sanitizer.AllowedTags.Clear(); // Strict mode<br>    }<br>    <br>    public async Task InvokeAsync(HttpContext context)<br>    {<br>        // Sadece POST, PUT, PATCH isteklerini kontrol et<br>        if (HttpMethods.IsPost(context.Request.Method) || <br>            HttpMethods.IsPut(context.Request.Method) ||<br>            HttpMethods.IsPatch(context.Request.Method))<br>        {<br>            context.Request.EnableBuffering();<br>            <br>            var body = await new StreamReader(context.Request.Body).ReadToEndAsync();<br>            context.Request.Body.Position = 0;<br>            <br>            if (ContainsPotentialXss(body))<br>            {<br>                _logger.LogWarning(<br>                    &quot;Potential Stored XSS attempt detected. IP: {IP}, Endpoint: {Endpoint}&quot;,<br>                    context.Connection.RemoteIpAddress,<br>                    context.Request.Path);<br>                <br>                context.Response.StatusCode = 400;<br>                await context.Response.WriteAsJsonAsync(new <br>                { <br>                    error = &quot;Request contains potentially dangerous content&quot; <br>                });<br>                return;<br>            }<br>        }<br>        <br>        await _next(context);<br>    }<br>    <br>    private bool ContainsPotentialXss(string input)<br>    {<br>        var xssPatterns = new[]<br>        {<br>            @&quot;&lt;script[\s\S]*?&gt;&quot;,<br>            @&quot;javascript:&quot;,<br>            @&quot;on\w+\s*=&quot;,<br>            @&quot;&lt;iframe&quot;,<br>            @&quot;&lt;object&quot;,<br>            @&quot;&lt;embed&quot;,<br>            @&quot;eval\s*\(&quot;,<br>            @&quot;expression\s*\(&quot;<br>        };<br>        <br>        return xssPatterns.Any(pattern =&gt; <br>            Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase));<br>    }<br>}<br>// Program.cs<br>app.UseMiddleware&lt;XssSanitizationMiddleware&gt;();</pre><p><strong>8. Rich Text Editor İçeriği İçin Özel Sanitization:</strong></p><pre>public class RichTextSanitizer<br>{<br>    private readonly HtmlSanitizer _sanitizer;<br>    <br>    public RichTextSanitizer()<br>    {<br>        _sanitizer = new HtmlSanitizer();<br>        <br>        // Rich text için izin verilen tag&#39;ler<br>        var allowedTags = new[] <br>        { <br>            &quot;p&quot;, &quot;br&quot;, &quot;strong&quot;, &quot;em&quot;, &quot;u&quot;, &quot;h1&quot;, &quot;h2&quot;, &quot;h3&quot;, <br>            &quot;ul&quot;, &quot;ol&quot;, &quot;li&quot;, &quot;a&quot;, &quot;blockquote&quot;, &quot;code&quot;, &quot;pre&quot; <br>        };<br>        <br>        _sanitizer.AllowedTags.Clear();<br>        foreach (var tag in allowedTags)<br>            _sanitizer.AllowedTags.Add(tag);<br>            <br>        // Sadece güvenli attribute&#39;lar<br>        _sanitizer.AllowedAttributes.Clear();<br>        _sanitizer.AllowedAttributes.Add(&quot;href&quot;);<br>        _sanitizer.AllowedAttributes.Add(&quot;title&quot;);<br>        _sanitizer.AllowedAttributes.Add(&quot;class&quot;);<br>        <br>        // Sadece güvenli URL scheme&#39;leri<br>        _sanitizer.AllowedSchemes.Clear();<br>        _sanitizer.AllowedSchemes.Add(&quot;http&quot;);<br>        _sanitizer.AllowedSchemes.Add(&quot;https&quot;);<br>        _sanitizer.AllowedSchemes.Add(&quot;mailto&quot;);<br>        <br>        // CSS kontrolü<br>        _sanitizer.AllowedCssProperties.Clear();<br>    }<br>    <br>    public string SanitizeRichText(string html)<br>    {<br>        return _sanitizer.Sanitize(html);<br>    }<br>}</pre><p><strong>9. Audit ve Monitoring:</strong></p><pre>public class XssAuditService : IXssAuditService<br>{<br>    private readonly ILogger&lt;XssAuditService&gt; _logger;<br>    private readonly ApplicationDbContext _context;<br>    <br>    public async Task LogSuspiciousActivity(string userId, string input, string endpoint)<br>    {<br>        var audit = new SecurityAuditLog<br>        {<br>            UserId = userId,<br>            Activity = &quot;Potential XSS Attempt&quot;,<br>            Details = $&quot;Endpoint: {endpoint}, Input: {input.Substring(0, Math.Min(200, input.Length))}&quot;,<br>            Timestamp = DateTime.UtcNow,<br>            IpAddress = GetCurrentIpAddress()<br>        };<br>        <br>        _context.SecurityAuditLogs.Add(audit);<br>        await _context.SaveChangesAsync();<br>        <br>        _logger.LogWarning(<br>            &quot;Suspicious XSS attempt logged for user {UserId} at {Endpoint}&quot;,<br>            userId, endpoint);<br>    }<br>}</pre><p><strong>10. Unit Testing — XSS Sanitization Testleri:</strong></p><pre>public class SanitizationServiceTests<br>{<br>    private readonly SanitizationService _sanitizer;<br>    <br>    public SanitizationServiceTests()<br>    {<br>        _sanitizer = new SanitizationService();<br>    }<br>    <br>    [Theory]<br>    [InlineData(&quot;&lt;script&gt;alert(&#39;XSS&#39;)&lt;/script&gt;&quot;, &quot;&quot;)]<br>    [InlineData(&quot;&lt;img src=x onerror=alert(&#39;XSS&#39;)&gt;&quot;, &quot;&quot;)]<br>    [InlineData(&quot;&lt;a href=&#39;javascript:alert(1)&#39;&gt;Click&lt;/a&gt;&quot;, &quot;Click&quot;)]<br>    [InlineData(&quot;Normal text&quot;, &quot;Normal text&quot;)]<br>    [InlineData(&quot;&lt;b&gt;Bold text&lt;/b&gt;&quot;, &quot;&lt;b&gt;Bold text&lt;/b&gt;&quot;)]<br>    public void Sanitize_ShouldRemoveDangerousContent(string input, string expected)<br>    {<br>        // Act<br>        var result = _sanitizer.Sanitize(input);<br>        <br>        // Assert<br>        Assert.Equal(expected, result);<br>    }<br>}</pre><p><strong>11. Veritabanından Okurken Double Encoding Önleme:</strong></p><pre>// YANLIŞ - Double encoding<br>public class BookDto<br>{<br>    public string Title { get; set; } // Veritabanında zaten sanitized<br>    <br>    public string GetTitle()<br>    {<br>        // Bu double encoding&#39;e neden olur - YAPMAYIN<br>        return HtmlEncoder.Default.Encode(Title);<br>    }<br>}<br>// DOĞRU - Veritabanına kaydetmeden önce sanitize et, okurken olduğu gibi döndür<br>public class BookDto<br>{<br>    public string Title { get; set; } // Zaten temiz<br>    <br>    // JSON serialize ederken otomatik encode olur<br>}</pre><p><strong>Kritik Best Practices:</strong></p><ul><li><strong>Whitelist yaklaşımı:</strong> Neyin güvenli olduğunu belirle, geri kalanı reddet (blacklist yerine)</li><li><strong>Sanitize at Input:</strong> Veriyi veritabanına kaydetmeden ÖNCE temizle</li><li><strong>Context-aware encoding:</strong> HTML context, JavaScript context, URL context için farklı encoding kullan</li><li><strong>Regular updates:</strong> HtmlSanitizer gibi kütüphaneleri güncel tut</li><li><strong>Defense in Depth:</strong> Hem input hem output seviyesinde koruma uygula</li><li><strong>User roles:</strong> Admin kullanıcılar için bile HTML injection’a izin verme</li><li><strong>Rich text dikkat:</strong> WYSIWYG editor kullanıyorsanız çok dikkatli olun</li><li><strong>Third-party content:</strong> Dış kaynaklardan gelen içeriği asla güvenme</li><li><strong>Testing:</strong> Penetration testing ve automated security scanning yap</li><li><strong>Education:</strong> Development team’e XSS awareness eğitimi ver</li></ul><p>Stored XSS, Reflected XSS’den çok daha tehlikelidir çünkü bir kez enjekte edilen kod tüm kullanıcıları sürekli etkiler. Bu nedenle katmanlı ve kapsamlı bir savunma stratejisi şarttır.</p><h3>ENCODER(HtmlEncoder/javaScriptEncoder/UrlEncoder nedir ?)</h3><p>asp.net core içerisinde gömülü olarak gelen Controller seviyesinde verileri nasıl encode edebiliriz buna yarayan sistemlerdir bunlar. Kötü amaçlı html js url’i encode ederek zararsız hale getirir.</p><h3>SQL Injection Saldırılarını Tespit ve Loglama</h3><p>SQL injection saldırılarını tespit edip, saldırganın IP adresini loglama ve hukuki süreç için hazırlama konusunu detaylı açıklayacağım.</p><h3>SQL Injection Detection Middleware</h3><pre>public class SQLInjectionDetectionMiddleware<br>{<br>    private readonly RequestDelegate _next;<br>    private readonly ILogger&lt;SQLInjectionDetectionMiddleware&gt; _logger;<br>    private readonly ISQLInjectionLogger _sqlInjectionLogger;<br>    private readonly IConfiguration _config;<br>    <br>    private static readonly string[] SQLInjectionPatterns = {<br>        @&quot;(\%27)|(\&#39;)|(\-\-)|(\%23)|(#)&quot;,<br>        @&quot;((\%3D)|(=))[^\n]*((\%27)|(\&#39;)|(\-\-)|(\%23)|(#))&quot;,<br>        @&quot;w*((\%27)|(\&#39;)){1}((\%6F)|o|(\%4F))((\%72)|r|(\%52))&quot;,<br>        @&quot;((\%27)|(\&#39;)){1}union&quot;,<br>        @&quot;exec(\s|\+)+(s|x)p\w+&quot;,<br>        @&quot;union(.|\n)*select&quot;,<br>        @&quot;select(.|\n)*from&quot;,<br>        @&quot;insert(.|\n)*into&quot;,<br>        @&quot;delete(.|\n)*from&quot;,<br>        @&quot;drop(.|\n)*table&quot;,<br>        @&quot;create(.|\n)*table&quot;,<br>        @&quot;alter(.|\n)*table&quot;,<br>        @&quot;update(.|\n)*set&quot;,<br>        @&quot;(\%27)|(\&#39;)\s*(or|and)\s*(\%27)|(\&#39;)&quot;,<br>        @&quot;(\%27)|(\&#39;)\s*=\s*(\%27)|(\&#39;)&quot;,<br>        @&quot;1\s*=\s*1&quot;,<br>        @&quot;(\%27)|(\&#39;)\s*(or|and)\s*1\s*=\s*1&quot;<br>    };<br>    <br>    public SQLInjectionDetectionMiddleware(<br>        RequestDelegate next, <br>        ILogger&lt;SQLInjectionDetectionMiddleware&gt; logger,<br>        ISQLInjectionLogger sqlInjectionLogger,<br>        IConfiguration config)<br>    {<br>        _next = next;<br>        _logger = logger;<br>        _sqlInjectionLogger = sqlInjectionLogger;<br>        _config = config;<br>    }<br>    <br>    public async Task InvokeAsync(HttpContext context)<br>    {<br>        // Request body&#39;yi oku<br>        var originalBodyStream = context.Request.Body;<br>        using var bodyReader = new StreamReader(context.Request.Body);<br>        var bodyContent = await bodyReader.ReadToEndAsync();<br>        <br>        // Stream&#39;i reset et<br>        context.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(bodyContent));<br>        <br>        // SQL Injection kontrolü<br>        var detectionResult = DetectSQLInjection(context, bodyContent);<br>        <br>        if (detectionResult.IsDetected)<br>        {<br>            var clientIP = GetClientIPAddress(context);<br>            var attackInfo = await _sqlInjectionLogger.LogSQLInjectionAttemptAsync(<br>                clientIP, <br>                context.Request.Path, <br>                context.Request.Method,<br>                detectionResult.DetectedPatterns,<br>                bodyContent,<br>                context.Request.QueryString.ToString(),<br>                GetUserAgent(context),<br>                GetHeaders(context)<br>            );<br>            <br>            // Saldırı tespit edildi - istek engelle<br>            context.Response.StatusCode = 400;<br>            await context.Response.WriteAsync(&quot;Bad Request&quot;);<br>            <br>            // Gerçek zamanlı alert gönder<br>            await SendRealTimeAlert(attackInfo);<br>            return;<br>        }<br>        <br>        // Normal işleme devam et<br>        await _next(context);<br>    }<br>    <br>    private SQLInjectionDetectionResult DetectSQLInjection(HttpContext context, string bodyContent)<br>    {<br>        var detectedPatterns = new List&lt;string&gt;();<br>        var allContent = $&quot;{context.Request.QueryString} {bodyContent}&quot;;<br>        <br>        foreach (var pattern in SQLInjectionPatterns)<br>        {<br>            if (Regex.IsMatch(allContent, pattern, RegexOptions.IgnoreCase))<br>            {<br>                detectedPatterns.Add(pattern);<br>            }<br>        }<br>        <br>        // Header kontrolü<br>        foreach (var header in context.Request.Headers)<br>        {<br>            foreach (var pattern in SQLInjectionPatterns)<br>            {<br>                if (Regex.IsMatch(header.Value.ToString(), pattern, RegexOptions.IgnoreCase))<br>                {<br>                    detectedPatterns.Add($&quot;Header:{header.Key}:{pattern}&quot;);<br>                }<br>            }<br>        }<br>        <br>        return new SQLInjectionDetectionResult<br>        {<br>            IsDetected = detectedPatterns.Any(),<br>            DetectedPatterns = detectedPatterns<br>        };<br>    }<br>    <br>    private IPAddress GetClientIPAddress(HttpContext context)<br>    {<br>        // Proxy arkasındaki gerçek IP&#39;yi al<br>        var xForwardedFor = context.Request.Headers[&quot;X-Forwarded-For&quot;].FirstOrDefault();<br>        if (!string.IsNullOrEmpty(xForwardedFor))<br>        {<br>            var ips = xForwardedFor.Split(&#39;,&#39;);<br>            if (IPAddress.TryParse(ips[0].Trim(), out var ip))<br>                return ip;<br>        }<br>        <br>        var xRealIP = context.Request.Headers[&quot;X-Real-IP&quot;].FirstOrDefault();<br>        if (!string.IsNullOrEmpty(xRealIP) &amp;&amp; IPAddress.TryParse(xRealIP, out var realIP))<br>            return realIP;<br>        <br>        var cfConnectingIP = context.Request.Headers[&quot;CF-Connecting-IP&quot;].FirstOrDefault();<br>        if (!string.IsNullOrEmpty(cfConnectingIP) &amp;&amp; IPAddress.TryParse(cfConnectingIP, out var cfIP))<br>            return cfIP;<br>        <br>        return context.Connection.RemoteIpAddress ?? IPAddress.None;<br>    }<br>    <br>    private string GetUserAgent(HttpContext context)<br>    {<br>        return context.Request.Headers[&quot;User-Agent&quot;].FirstOrDefault() ?? &quot;Unknown&quot;;<br>    }<br>    <br>    private Dictionary&lt;string, string&gt; GetHeaders(HttpContext context)<br>    {<br>        return context.Request.Headers.ToDictionary(h =&gt; h.Key, h =&gt; h.Value.ToString());<br>    }<br>    <br>    private async Task SendRealTimeAlert(SQLInjectionAttack attack)<br>    {<br>        // Email, Slack, Teams vb. ile gerçek zamanlı bildirim<br>        // Bu kısım sonraki örneklerde detaylandırılacak<br>    }<br>}<br><br>public class SQLInjectionDetectionResult<br>{<br>    public bool IsDetected { get; set; }<br>    public List&lt;string&gt; DetectedPatterns { get; set; } = new();<br>}</pre><h3>SQL Injection Logger Service</h3><pre>public interface ISQLInjectionLogger<br>{<br>    Task&lt;SQLInjectionAttack&gt; LogSQLInjectionAttemptAsync(<br>        IPAddress sourceIP,<br>        string endpoint,<br>        string method,<br>        List&lt;string&gt; detectedPatterns,<br>        string requestBody,<br>        string queryString,<br>        string userAgent,<br>        Dictionary&lt;string, string&gt; headers);<br>    <br>    Task&lt;List&lt;SQLInjectionAttack&gt;&gt; GetAttacksByIPAsync(IPAddress ip);<br>    Task&lt;List&lt;SQLInjectionAttack&gt;&gt; GetRecentAttacksAsync(TimeSpan timeSpan);<br>    Task GenerateForensicReportAsync(IPAddress ip);<br>}<br>public class SQLInjectionLogger : ISQLInjectionLogger<br>{<br>    private readonly AppDbContext _context;<br>    private readonly ILogger&lt;SQLInjectionLogger&gt; _logger;<br>    private readonly IGeoLocationService _geoLocationService;<br>    private readonly IEmailService _emailService;<br>    <br>    public SQLInjectionLogger(<br>        AppDbContext context, <br>        ILogger&lt;SQLInjectionLogger&gt; logger,<br>        IGeoLocationService geoLocationService,<br>        IEmailService emailService)<br>    {<br>        _context = context;<br>        _logger = logger;<br>        _geoLocationService = geoLocationService;<br>        _emailService = emailService;<br>    }<br>    <br>    public async Task&lt;SQLInjectionAttack&gt; LogSQLInjectionAttemptAsync(<br>        IPAddress sourceIP,<br>        string endpoint,<br>        string method,<br>        List&lt;string&gt; detectedPatterns,<br>        string requestBody,<br>        string queryString,<br>        string userAgent,<br>        Dictionary&lt;string, string&gt; headers)<br>    {<br>        // Coğrafi konum bilgisi al<br>        var geoLocation = await _geoLocationService.GetLocationAsync(sourceIP);<br>        <br>        var attack = new SQLInjectionAttack<br>        {<br>            Id = Guid.NewGuid(),<br>            SourceIP = sourceIP.ToString(),<br>            Endpoint = endpoint,<br>            Method = method,<br>            DetectedPatterns = string.Join(&quot;; &quot;, detectedPatterns),<br>            RequestBody = requestBody,<br>            QueryString = queryString,<br>            UserAgent = userAgent,<br>            Headers = JsonSerializer.Serialize(headers),<br>            Timestamp = DateTime.UtcNow,<br>            <br>            // Coğrafi bilgiler<br>            Country = geoLocation.Country,<br>            City = geoLocation.City,<br>            ISP = geoLocation.ISP,<br>            Organization = geoLocation.Organization,<br>            Latitude = geoLocation.Latitude,<br>            Longitude = geoLocation.Longitude,<br>            <br>            // Risk seviyesi<br>            RiskLevel = CalculateRiskLevel(detectedPatterns, geoLocation),<br>            <br>            // Forensic hash<br>            ForensicHash = GenerateForensicHash(sourceIP, endpoint, requestBody, queryString, userAgent)<br>        };<br>        <br>        _context.SQLInjectionAttacks.Add(attack);<br>        await _context.SaveChangesAsync();<br>        <br>        // Kritik log<br>        _logger.LogCritical(<br>            &quot;SQL Injection Attack Detected! IP: {IP}, Country: {Country}, Endpoint: {Endpoint}, Patterns: {Patterns}&quot;,<br>            sourceIP, geoLocation.Country, endpoint, string.Join(&quot;, &quot;, detectedPatterns));<br>        <br>        // Eğer yüksek risk seviyesindeyse anında bildirim gönder<br>        if (attack.RiskLevel &gt;= RiskLevel.High)<br>        {<br>            await SendImmediateAlert(attack);<br>        }<br>        <br>        return attack;<br>    }<br>    <br>    private RiskLevel CalculateRiskLevel(List&lt;string&gt; patterns, GeoLocation geoLocation)<br>    {<br>        var score = 0;<br>        <br>        // Pattern sayısına göre puan<br>        score += patterns.Count * 10;<br>        <br>        // Tehlikeli pattern&#39;lara ekstra puan<br>        if (patterns.Any(p =&gt; p.Contains(&quot;union&quot;) || p.Contains(&quot;drop&quot;) || p.Contains(&quot;delete&quot;)))<br>            score += 50;<br>        <br>        // Şüpheli ülkelerden geliyorsa ekstra puan<br>        var suspiciousCountries = new[] { &quot;CN&quot;, &quot;RU&quot;, &quot;KP&quot; }; // Örnek<br>        if (suspiciousCountries.Contains(geoLocation.CountryCode))<br>            score += 30;<br>        <br>        return score switch<br>        {<br>            &gt;= 100 =&gt; RiskLevel.Critical,<br>            &gt;= 70 =&gt; RiskLevel.High,<br>            &gt;= 40 =&gt; RiskLevel.Medium,<br>            _ =&gt; RiskLevel.Low<br>        };<br>    }<br>    <br>    private string GenerateForensicHash(IPAddress ip, string endpoint, string body, string query, string userAgent)<br>    {<br>        var data = $&quot;{ip}|{endpoint}|{body}|{query}|{userAgent}|{DateTime.UtcNow:yyyy-MM-dd}&quot;;<br>        using var sha256 = SHA256.Create();<br>        var hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(data));<br>        return Convert.ToBase64String(hash);<br>    }<br>    <br>    private async Task SendImmediateAlert(SQLInjectionAttack attack)<br>    {<br>        var subject = $&quot;CRITICAL: SQL Injection Attack from {attack.SourceIP}&quot;;<br>        var body = $@&quot;<br>            SQL Injection attack detected at {attack.Timestamp:yyyy-MM-dd HH:mm:ss} UTC<br>            <br>            Source IP: {attack.SourceIP}<br>            Location: {attack.City}, {attack.Country}<br>            ISP: {attack.ISP}<br>            Endpoint: {attack.Endpoint}<br>            Method: {attack.Method}<br>            Risk Level: {attack.RiskLevel}<br>            <br>            Detected Patterns: {attack.DetectedPatterns}<br>            <br>            Forensic Hash: {attack.ForensicHash}<br>            <br>            This incident has been automatically logged for legal reporting.<br>        &quot;;<br>        <br>        await _emailService.SendAlertEmailAsync(&quot;security@yourcompany.com&quot;, subject, body);<br>    }<br>    <br>    public async Task GenerateForensicReportAsync(IPAddress ip)<br>    {<br>        var attacks = await _context.SQLInjectionAttacks<br>            .Where(a =&gt; a.SourceIP == ip.ToString())<br>            .OrderBy(a =&gt; a.Timestamp)<br>            .ToListAsync();<br>        <br>        var report = new ForensicReport<br>        {<br>            GeneratedAt = DateTime.UtcNow,<br>            SourceIP = ip.ToString(),<br>            TotalAttacks = attacks.Count,<br>            FirstAttack = attacks.FirstOrDefault()?.Timestamp,<br>            LastAttack = attacks.LastOrDefault()?.Timestamp,<br>            AttackDetails = attacks<br>        };<br>        <br>        // PDF rapor oluştur<br>        await GeneratePDFReport(report);<br>    }<br>}</pre><h3>Database Models</h3><pre>public class SQLInjectionAttack<br>{<br>    public Guid Id { get; set; }<br>    public string SourceIP { get; set; }<br>    public string Endpoint { get; set; }<br>    public string Method { get; set; }<br>    public string DetectedPatterns { get; set; }<br>    public string RequestBody { get; set; }<br>    public string QueryString { get; set; }<br>    public string UserAgent { get; set; }<br>    public string Headers { get; set; }<br>    public DateTime Timestamp { get; set; }<br>    <br>    // Coğrafi bilgiler<br>    public string Country { get; set; }<br>    public string CountryCode { get; set; }<br>    public string City { get; set; }<br>    public string ISP { get; set; }<br>    public string Organization { get; set; }<br>    public double? Latitude { get; set; }<br>    public double? Longitude { get; set; }<br>    <br>    // Analiz bilgileri<br>    public RiskLevel RiskLevel { get; set; }<br>    public string ForensicHash { get; set; }<br>    public bool ReportedToAuthorities { get; set; }<br>    public DateTime? ReportedAt { get; set; }<br>    public string ReportReference { get; set; }<br>}<br>public enum RiskLevel<br>{<br>    Low = 1,<br>    Medium = 2,<br>    High = 3,<br>    Critical = 4<br>}<br>public class GeoLocation<br>{<br>    public string Country { get; set; }<br>    public string CountryCode { get; set; }<br>    public string City { get; set; }<br>    public string ISP { get; set; }<br>    public string Organization { get; set; }<br>    public double? Latitude { get; set; }<br>    public double? Longitude { get; set; }<br>}</pre><h3>Hukuki Rapor Oluşturma</h3><pre>public class LegalReportService<br>{<br>    private readonly ISQLInjectionLogger _logger;<br>    private readonly IConfiguration _config;<br>    <br>    public async Task&lt;string&gt; GenerateLegalReportAsync(IPAddress attackerIP, string reportReason)<br>    {<br>        var attacks = await _logger.GetAttacksByIPAsync(attackerIP);<br>        <br>        var report = new LegalReport<br>        {<br>            ReportId = Guid.NewGuid().ToString(),<br>            GeneratedAt = DateTime.UtcNow,<br>            CompanyInfo = GetCompanyInfo(),<br>            AttackerIP = attackerIP.ToString(),<br>            AttackSummary = GenerateAttackSummary(attacks),<br>            TechnicalDetails = GenerateTechnicalDetails(attacks),<br>            LegalBasis = GetLegalBasis(),<br>            RequestedAction = reportReason<br>        };<br>        <br>        return GenerateReportDocument(report);<br>    }<br>    <br>    private CompanyInfo GetCompanyInfo()<br>    {<br>        return new CompanyInfo<br>        {<br>            Name = _config[&quot;Company:Name&quot;],<br>            Address = _config[&quot;Company:Address&quot;],<br>            ContactPerson = _config[&quot;Company:SecurityContact&quot;],<br>            Email = _config[&quot;Company:SecurityEmail&quot;],<br>            Phone = _config[&quot;Company:SecurityPhone&quot;]<br>        };<br>    }<br>    <br>    private string GenerateReportDocument(LegalReport report)<br>    {<br>        return $@&quot;<br># CYBERSUÇ BAŞVURU RAPORU**Rapor No:** {report.ReportId}<br>**Tarih:** {report.GeneratedAt:dd.MM.yyyy HH:mm:ss}<br>## 1. BAŞVURAN BİLGİLERİ<br>**Şirket:** {report.CompanyInfo.Name}<br>**Adres:** {report.CompanyInfo.Address}<br>**Yetkili Kişi:** {report.CompanyInfo.ContactPerson}<br>**E-posta:** {report.CompanyInfo.Email}<br>**Telefon:** {report.CompanyInfo.Phone}<br>## 2. SALDIRI ÖZETİ<br>**Saldırgan IP Adresi:** {report.AttackerIP}<br>**Toplam Saldırı Sayısı:** {report.AttackSummary.TotalAttacks}<br>**İlk Saldırı:** {report.AttackSummary.FirstAttack:dd.MM.yyyy HH:mm:ss}<br>**Son Saldırı:** {report.AttackSummary.LastAttack:dd.MM.yyyy HH:mm:ss}<br>**Risk Seviyesi:** {report.AttackSummary.HighestRiskLevel}<br>## 3. TEKNİK DETAYLAR<br>{report.TechnicalDetails}<br>## 4. HUKUKİ DAYANAK<br>{report.LegalBasis}<br>## 5. TALEBİMİZ<br>{report.RequestedAction}<br>Bu rapor otomatik güvenlik sistemlerimiz tarafından oluşturulmuş olup, <br>tüm veriler sistem loglarında kayıtlıdır ve mahkeme talebinde ibraz edilebilir.<br>---<br>Bu belge {report.GeneratedAt:dd.MM.yyyy HH:mm:ss} tarihinde otomatik olarak oluşturulmuştur.<br>        &quot;;<br>    }<br>}<br></pre><h3>Polise Bildirim API’si</h3><pre>[ApiController]<br>[Route(&quot;api/[controller]&quot;)]<br>[Authorize(Roles = &quot;SecurityAdmin&quot;)]<br>public class CyberCrimeReportController : ControllerBase<br>{<br>    private readonly ISQLInjectionLogger _logger;<br>    private readonly LegalReportService _reportService;<br>    <br>    [HttpPost(&quot;report-to-authorities&quot;)]<br>    public async Task&lt;IActionResult&gt; ReportToAuthorities([FromBody] CyberCrimeReportRequest request)<br>    {<br>        if (!IPAddress.TryParse(request.AttackerIP, out var ip))<br>            return BadRequest(&quot;Invalid IP address&quot;);<br>        <br>        // Detaylı rapor oluştur<br>        var legalReport = await _reportService.GenerateLegalReportAsync(ip, request.Reason);<br>        <br>        // Raporun PDF versiyonunu oluştur<br>        var pdfBytes = await GeneratePDFReport(legalReport);<br>        <br>        // Kayıt güncelle<br>        await UpdateAttackRecordsAsReported(ip, request.ReportReference);<br>        <br>        // Otomatik e-posta gönder (opsiyonel)<br>        if (request.SendToAuthorities)<br>        {<br>            await SendReportToAuthorities(legalReport, pdfBytes);<br>        }<br>        <br>        return Ok(new<br>        {<br>            Message = &quot;Cybercrime report generated successfully&quot;,<br>            ReportId = Guid.NewGuid().ToString(),<br>            PDFSize = pdfBytes.Length,<br>            CanDownload = true<br>        });<br>    }<br>    <br>    [HttpGet(&quot;download-report/{attackerIP}&quot;)]<br>    public async Task&lt;IActionResult&gt; DownloadReport(string attackerIP)<br>    {<br>        if (!IPAddress.TryParse(attackerIP, out var ip))<br>            return BadRequest(&quot;Invalid IP address&quot;);<br>        <br>        var legalReport = await _reportService.GenerateLegalReportAsync(ip, &quot;Legal investigation&quot;);<br>        var pdfBytes = await GeneratePDFReport(legalReport);<br>        <br>        return File(pdfBytes, &quot;application/pdf&quot;, $&quot;cybercrime_report_{attackerIP}_{DateTime.Now:yyyyMMdd}.pdf&quot;);<br>    }<br>    <br>    private async Task UpdateAttackRecordsAsReported(IPAddress ip, string reportReference)<br>    {<br>        // Veritabanında saldırıları bildirildi olarak işaretle<br>        var attacks = await _context.SQLInjectionAttacks<br>            .Where(a =&gt; a.SourceIP == ip.ToString() &amp;&amp; !a.ReportedToAuthorities)<br>            .ToListAsync();<br>        <br>        foreach (var attack in attacks)<br>        {<br>            attack.ReportedToAuthorities = true;<br>            attack.ReportedAt = DateTime.UtcNow;<br>            attack.ReportReference = reportReference;<br>        }<br>        <br>        await _context.SaveChangesAsync();<br>    }<br>}<br>public class CyberCrimeReportRequest<br>{<br>    public string AttackerIP { get; set; }<br>    public string Reason { get; set; }<br>    public string ReportReference { get; set; }<br>    public bool SendToAuthorities { get; set; }<br>}</pre><h3>Gerçek Zamanlı İzleme Dashboard</h3><pre>[ApiController]<br>[Route(&quot;api/[controller]&quot;)]<br>public class SecurityDashboardController : ControllerBase<br>{<br>    private readonly ISQLInjectionLogger _logger;<br>    <br>    [HttpGet(&quot;live-attacks&quot;)]<br>    public async Task&lt;IActionResult&gt; GetLiveAttacks()<br>    {<br>        var recentAttacks = await _logger.GetRecentAttacksAsync(TimeSpan.FromHours(24));<br>        <br>        return Ok(new<br>        {<br>            TotalAttacks = recentAttacks.Count,<br>            HighRiskAttacks = recentAttacks.Count(a =&gt; a.RiskLevel &gt;= RiskLevel.High),<br>            TopAttackerIPs = recentAttacks<br>                .GroupBy(a =&gt; a.SourceIP)<br>                .OrderByDescending(g =&gt; g.Count())<br>                .Take(10)<br>                .Select(g =&gt; new { IP = g.Key, Count = g.Count() }),<br>            TopTargetedEndpoints = recentAttacks<br>                .GroupBy(a =&gt; a.Endpoint)<br>                .OrderByDescending(g =&gt; g.Count())<br>                .Take(10)<br>                .Select(g =&gt; new { Endpoint = g.Key, Count = g.Count() }),<br>            AttacksByCountry = recentAttacks<br>                .GroupBy(a =&gt; a.Country)<br>                .OrderByDescending(g =&gt; g.Count())<br>                .Select(g =&gt; new { Country = g.Key, Count = g.Count() })<br>        });<br>    }<br>}</pre><h3>Kurulum ve Yapılandırma</h3><pre>// Program.cs<br>builder.Services.AddScoped&lt;ISQLInjectionLogger, SQLInjectionLogger&gt;();<br>builder.Services.AddScoped&lt;LegalReportService&gt;();<br>builder.Services.AddScoped&lt;IGeoLocationService, GeoLocationService&gt;();<br>var app = builder.Build();<br>// Middleware&#39;i ekle (diğer middleware&#39;lerden önce)<br>app.UseMiddleware&lt;SQLInjectionDetectionMiddleware&gt;();<br>app.Run();</pre><h3>ASP.NET Web API’de Middleware Oluşturma ve Çalışma Prensibi</h3><p>Middleware, ASP.NET Core’da HTTP request pipeline’ında çalışan bileşenlerdir. Request’i işleyip response’u döndürene kadar geçen süreçte ara katman görevini üstlenirler. Asp.net projeleri katman katman çalışır. M</p><h3>Middleware Nasıl Çalışır?</h3><pre>Request → Middleware 1 → Middleware 2 → Middleware 3 → Controller<br>          ↓              ↓              ↓              ↓<br>Response ← Middleware 1 ← Middleware 2 ← Middleware 3 ← Controller</pre><p>Her middleware:</p><ol><li>Request’i işler</li><li>Sonraki middleware’e geçer veya pipeline’ı keser</li><li>Response dönüşünde tekrar işlem yapabilir</li></ol><h3>Basit Middleware Oluşturma</h3><h3>1. Inline Middleware (Lambda Expression)</h3><pre>// Program.cs<br>var builder = WebApplication.CreateBuilder(args);<br>var app = builder.Build();<br>// En basit middleware - inline<br>app.Use(async (context, next) =&gt;<br>{<br>    // Request işleme (gelen yön)<br>    Console.WriteLine($&quot;Request: {context.Request.Path}&quot;);<br>    <br>    // Sonraki middleware&#39;e geç<br>    await next(context);<br>    <br>    // Response işleme (dönen yön)<br>    Console.WriteLine($&quot;Response: {context.Response.StatusCode}&quot;);<br>});<br>app.MapControllers();<br>app.Run();</pre><h3>2. Class-based Middleware</h3><pre>public class CustomLoggingMiddleware<br>{<br>    private readonly RequestDelegate _next;<br>    private readonly ILogger&lt;CustomLoggingMiddleware&gt; _logger;<br>    <br>    // Constructor&#39;da RequestDelegate mutlaka olmalı<br>    public CustomLoggingMiddleware(RequestDelegate next, ILogger&lt;CustomLoggingMiddleware&gt; logger)<br>    {<br>        _next = next;<br>        _logger = logger;<br>    }<br>    <br>    // InvokeAsync veya Invoke metodu olmalı Böylece her gelen istekte çalışacak metotu belirleyebiliriz birden fazla metotta çalışabilir.<br>    public async Task InvokeAsync(HttpContext context)<br>    {<br>        var startTime = DateTime.UtcNow;<br>        <br>        // Request bilgilerini logla<br>        _logger.LogInformation(&quot;Request started: {Method} {Path} at {Time}&quot;, <br>            context.Request.Method, <br>            context.Request.Path, <br>            startTime);<br>        <br>        try<br>        {<br>            // Sonraki middleware&#39;e geç<br>            await _next(context);<br>        }<br>        catch (Exception ex)<br>        {<br>            _logger.LogError(ex, &quot;Request failed: {Method} {Path}&quot;, <br>                context.Request.Method, context.Request.Path);<br>            throw; // Exception&#39;ı yeniden fırlat<br>        }<br>        finally<br>        {<br>            var endTime = DateTime.UtcNow;<br>            var duration = endTime - startTime;<br>            <br>            _logger.LogInformation(&quot;Request completed: {Method} {Path} {StatusCode} in {Duration}ms&quot;, <br>                context.Request.Method, <br>                context.Request.Path, <br>                context.Response.StatusCode,<br>                duration.TotalMilliseconds);<br>        }<br>    }<br>}</pre><pre>// Kullanım<br>app.UseMiddleware&lt;CustomLoggingMiddleware&gt;();</pre><h3>Extension Method ile Middleware</h3><pre>public static class MiddlewareExtensions<br>{<br>    public static IApplicationBuilder UseCustomLogging(this IApplicationBuilder builder)<br>    {<br>        return builder.UseMiddleware&lt;CustomLoggingMiddleware&gt;();<br>    }<br>    <br>    // Parametreli extension<br>    public static IApplicationBuilder UseCustomAuth(this IApplicationBuilder builder, string secretKey)<br>    {<br>        return builder.UseMiddleware&lt;CustomAuthMiddleware&gt;(secretKey);<br>    }<br>}<br>// Kullanım<br>app.UseCustomLogging();<br>app.UseCustomAuth(&quot;my-secret-key&quot;);</pre><h3>Gerçek Dünya Örnekleri</h3><h3>1. Authentication Middleware</h3><pre>public class JwtAuthenticationMiddleware<br>{<br>    private readonly RequestDelegate _next;<br>    private readonly IConfiguration _config;<br>    private readonly ILogger&lt;JwtAuthenticationMiddleware&gt; _logger;<br>    <br>    public JwtAuthenticationMiddleware(<br>        RequestDelegate next, <br>        IConfiguration config,<br>        ILogger&lt;JwtAuthenticationMiddleware&gt; logger)<br>    {<br>        _next = next;<br>        _config = config;<br>        _logger = logger;<br>    }<br>    <br>    public async Task InvokeAsync(HttpContext context)<br>    {<br>        // Public endpoint&#39;ler için auth kontrolü atlama<br>        if (IsPublicEndpoint(context.Request.Path))<br>        {<br>            await _next(context);<br>            return;<br>        }<br>        <br>        var token = ExtractToken(context.Request);<br>        <br>        if (string.IsNullOrEmpty(token))<br>        {<br>            await HandleUnauthorized(context, &quot;Token not provided&quot;);<br>            return;<br>        }<br>        <br>        try<br>        {<br>            var principal = ValidateToken(token);<br>            context.User = principal;<br>            <br>            // User bilgilerini context&#39;e ekle<br>            context.Items[&quot;UserId&quot;] = principal.FindFirst(&quot;sub&quot;)?.Value;<br>            context.Items[&quot;UserRole&quot;] = principal.FindFirst(&quot;role&quot;)?.Value;<br>            <br>            await _next(context);<br>        }<br>        catch (SecurityTokenException ex)<br>        {<br>            _logger.LogWarning(&quot;Invalid token: {Error}&quot;, ex.Message);<br>            await HandleUnauthorized(context, &quot;Invalid token&quot;);<br>        }<br>    }<br>    <br>    private bool IsPublicEndpoint(PathString path)<br>    {<br>        var publicPaths = new[] { &quot;/api/auth/login&quot;, &quot;/api/auth/register&quot;, &quot;/api/health&quot; };<br>        return publicPaths.Any(p =&gt; path.StartsWithSegments(p));<br>    }<br>    <br>    private string ExtractToken(HttpRequest request)<br>    {<br>        var authHeader = request.Headers[&quot;Authorization&quot;].FirstOrDefault();<br>        if (authHeader?.StartsWith(&quot;Bearer &quot;) == true)<br>        {<br>            return authHeader.Substring(&quot;Bearer &quot;.Length).Trim();<br>        }<br>        <br>        // Query string&#39;den token alma (WebSocket için)<br>        return request.Query[&quot;access_token&quot;].FirstOrDefault();<br>    }<br>    <br>    private ClaimsPrincipal ValidateToken(string token)<br>    {<br>        var tokenHandler = new JwtSecurityTokenHandler();<br>        var key = Encoding.ASCII.GetBytes(_config[&quot;Jwt:SecretKey&quot;]);<br>        <br>        var validationParameters = new TokenValidationParameters<br>        {<br>            ValidateIssuerSigningKey = true,<br>            IssuerSigningKey = new SymmetricSecurityKey(key),<br>            ValidateIssuer = true,<br>            ValidIssuer = _config[&quot;Jwt:Issuer&quot;],<br>            ValidateAudience = true,<br>            ValidAudience = _config[&quot;Jwt:Audience&quot;],<br>            ValidateLifetime = true,<br>            ClockSkew = TimeSpan.Zero<br>        };<br>        <br>        var principal = tokenHandler.ValidateToken(token, validationParameters, out _);<br>        return principal;<br>    }<br>    <br>    private async Task HandleUnauthorized(HttpContext context, string message)<br>    {<br>        context.Response.StatusCode = 401;<br>        context.Response.ContentType = &quot;application/json&quot;;<br>        <br>        var response = new { error = &quot;Unauthorized&quot;, message = message };<br>        await context.Response.WriteAsync(JsonSerializer.Serialize(response));<br>    }<br>}</pre><h3>2. Request/Response Logging Middleware</h3><pre>public class RequestResponseLoggingMiddleware<br>{<br>    private readonly RequestDelegate _next;<br>    private readonly ILogger&lt;RequestResponseLoggingMiddleware&gt; _logger;<br>    <br>    public RequestResponseLoggingMiddleware(RequestDelegate next, ILogger&lt;RequestResponseLoggingMiddleware&gt; logger)<br>    {<br>        _next = next;<br>        _logger = logger;<br>    }<br>    <br>    public async Task InvokeAsync(HttpContext context)<br>    {<br>        // Request body&#39;yi okumak için stream&#39;i değiştir<br>        var originalBodyStream = context.Response.Body;<br>        <br>        using var responseBody = new MemoryStream();<br>        context.Response.Body = responseBody;<br>        <br>        // Request&#39;i logla<br>        await LogRequest(context);<br>        <br>        // Sonraki middleware&#39;e geç<br>        await _next(context);<br>        <br>        // Response&#39;u logla<br>        await LogResponse(context);<br>        <br>        // Orijinal response&#39;u geri yaz<br>        await responseBody.CopyToAsync(originalBodyStream);<br>    }<br>    <br>    private async Task LogRequest(HttpContext context)<br>    {<br>        var request = context.Request;<br>        <br>        // Request body&#39;yi oku<br>        request.EnableBuffering(); // Stream&#39;i tekrar okuyabilir hale getir<br>        var buffer = new byte[Convert.ToInt32(request.ContentLength)];<br>        await request.Body.ReadAsync(buffer, 0, buffer.Length);<br>        var requestBody = Encoding.UTF8.GetString(buffer);<br>        request.Body.Position = 0; // Stream&#39;i başa al<br>        <br>        var requestLog = new<br>        {<br>            Method = request.Method,<br>            Path = request.Path,<br>            QueryString = request.QueryString.ToString(),<br>            Headers = request.Headers.ToDictionary(h =&gt; h.Key, h =&gt; h.Value.ToString()),<br>            Body = requestBody,<br>            Timestamp = DateTime.UtcNow,<br>            IP = context.Connection.RemoteIpAddress?.ToString()<br>        };<br>        <br>        _logger.LogInformation(&quot;Request: {@RequestLog}&quot;, requestLog);<br>    }<br>    <br>    private async Task LogResponse(HttpContext context)<br>    {<br>        var response = context.Response;<br>        response.Body.Seek(0, SeekOrigin.Begin);<br>        <br>        var responseBody = await new StreamReader(response.Body).ReadToEndAsync();<br>        response.Body.Seek(0, SeekOrigin.Begin);<br>        <br>        var responseLog = new<br>        {<br>            StatusCode = response.StatusCode,<br>            Headers = response.Headers.ToDictionary(h =&gt; h.Key, h =&gt; h.Value.ToString()),<br>            Body = responseBody,<br>            Timestamp = DateTime.UtcNow<br>        };<br>        <br>        _logger.LogInformation(&quot;Response: {@ResponseLog}&quot;, responseLog);<br>    }<br>}</pre><h3>3. Rate Limiting Middleware</h3><pre>public class RateLimitingMiddleware<br>{<br>    private readonly RequestDelegate _next;<br>    private readonly IMemoryCache _cache;<br>    private readonly RateLimitOptions _options;<br>    private readonly ILogger&lt;RateLimitingMiddleware&gt; _logger;<br>    <br>    public RateLimitingMiddleware(<br>        RequestDelegate next, <br>        IMemoryCache cache,<br>        IOptions&lt;RateLimitOptions&gt; options,<br>        ILogger&lt;RateLimitingMiddleware&gt; logger)<br>    {<br>        _next = next;<br>        _cache = cache;<br>        _options = options.Value;<br>        _logger = logger;<br>    }<br>    <br>    public async Task InvokeAsync(HttpContext context)<br>    {<br>        var clientId = GetClientIdentifier(context);<br>        var endpoint = context.Request.Path.ToString();<br>        var key = $&quot;rate_limit_{clientId}_{endpoint}&quot;;<br>        <br>        // Rate limit kontrolü<br>        if (!await IsRequestAllowed(key, clientId, endpoint))<br>        {<br>            await HandleRateLimitExceeded(context, clientId);<br>            return;<br>        }<br>        <br>        await _next(context);<br>    }<br>    <br>    private string GetClientIdentifier(HttpContext context)<br>    {<br>        // IP based rate limiting<br>        var ip = context.Connection.RemoteIpAddress?.ToString();<br>        <br>        // User based rate limiting (eğer authenticate ise)<br>        var userId = context.User?.FindFirst(&quot;sub&quot;)?.Value;<br>        <br>        return userId ?? ip ?? &quot;unknown&quot;;<br>    }<br>    <br>    private async Task&lt;bool&gt; IsRequestAllowed(string key, string clientId, string endpoint)<br>    {<br>        var now = DateTime.UtcNow;<br>        var windowStart = now.AddMinutes(-_options.WindowSizeInMinutes);<br>        <br>        // Cache&#39;den mevcut istekleri al<br>        var requests = _cache.GetOrCreate(key, entry =&gt;<br>        {<br>            entry.SlidingExpiration = TimeSpan.FromMinutes(_options.WindowSizeInMinutes);<br>            return new List&lt;DateTime&gt;();<br>        });<br>        <br>        // Eski istekleri temizle<br>        requests.RemoveAll(time =&gt; time &lt; windowStart);<br>        <br>        // Limit kontrolü<br>        if (requests.Count &gt;= _options.MaxRequests)<br>        {<br>            _logger.LogWarning(&quot;Rate limit exceeded for client {ClientId} on endpoint {Endpoint}&quot;, <br>                clientId, endpoint);<br>            return false;<br>        }<br>        <br>        // Yeni isteği ekle<br>        requests.Add(now);<br>        return true;<br>    }<br>    <br>    private async Task HandleRateLimitExceeded(HttpContext context, string clientId)<br>    {<br>        context.Response.StatusCode = 429; // Too Many Requests<br>        context.Response.ContentType = &quot;application/json&quot;;<br>        <br>        var response = new<br>        {<br>            error = &quot;Rate limit exceeded&quot;,<br>            message = $&quot;Too many requests. Try again in {_options.WindowSizeInMinutes} minutes.&quot;,<br>            retryAfter = _options.WindowSizeInMinutes * 60 // seconds<br>        };<br>        <br>        context.Response.Headers.Add(&quot;Retry-After&quot;, (response.retryAfter).ToString());<br>        await context.Response.WriteAsync(JsonSerializer.Serialize(response));<br>    }<br>}<br><br>public class RateLimitOptions<br>{<br>    public int MaxRequests { get; set; } = 100;<br>    public int WindowSizeInMinutes { get; set; } = 1;<br>}</pre><h3>4. Error Handling Middleware</h3><pre>public class GlobalExceptionHandlingMiddleware<br>{<br>    private readonly RequestDelegate _next;<br>    private readonly ILogger&lt;GlobalExceptionHandlingMiddleware&gt; _logger;<br>    private readonly IHostEnvironment _env;<br>    <br>    public GlobalExceptionHandlingMiddleware(<br>        RequestDelegate next, <br>        ILogger&lt;GlobalExceptionHandlingMiddleware&gt; logger,<br>        IHostEnvironment env)<br>    {<br>        _next = next;<br>        _logger = logger;<br>        _env = env;<br>    }<br>    <br>    public async Task InvokeAsync(HttpContext context)<br>    {<br>        try<br>        {<br>            await _next(context);<br>        }<br>        catch (Exception ex)<br>        {<br>            _logger.LogError(ex, &quot;An unhandled exception occurred while processing the request&quot;);<br>            await HandleExceptionAsync(context, ex);<br>        }<br>    }<br>    <br>    private async Task HandleExceptionAsync(HttpContext context, Exception exception)<br>    {<br>        context.Response.ContentType = &quot;application/json&quot;;<br>        <br>        var response = exception switch<br>        {<br>            NotFoundException ex =&gt; new ErrorResponse<br>            {<br>                StatusCode = 404,<br>                Message = ex.Message,<br>                Details = _env.IsDevelopment() ? ex.StackTrace : null<br>            },<br>            ValidationException ex =&gt; new ErrorResponse<br>            {<br>                StatusCode = 400,<br>                Message = &quot;Validation failed&quot;,<br>                Details = ex.Errors<br>            },<br>            UnauthorizedAccessException ex =&gt; new ErrorResponse<br>            {<br>                StatusCode = 401,<br>                Message = &quot;Unauthorized access&quot;<br>            },<br>            _ =&gt; new ErrorResponse<br>            {<br>                StatusCode = 500,<br>                Message = _env.IsDevelopment() ? exception.Message : &quot;An internal server error occurred&quot;,<br>                Details = _env.IsDevelopment() ? exception.StackTrace : null<br>            }<br>        };<br>        <br>        context.Response.StatusCode = response.StatusCode;<br>        await context.Response.WriteAsync(JsonSerializer.Serialize(response));<br>    }<br>}<br>public class ErrorResponse<br>{<br>    public int StatusCode { get; set; }<br>    public string Message { get; set; }<br>    public object Details { get; set; }<br>}<br>// Custom exceptions<br>public class NotFoundException : Exception<br>{<br>    public NotFoundException(string message) : base(message) { }<br>}<br>public class ValidationException : Exception<br>{<br>    public object Errors { get; set; }<br>    public ValidationException(string message, object errors) : base(message)<br>    {<br>        Errors = errors;<br>    }<br>}</pre><h3>Middleware Pipeline Sırası</h3><pre>var builder = WebApplication.CreateBuilder(args);<br>// Services<br>builder.Services.AddControllers();<br>builder.Services.AddMemoryCache();<br>builder.Services.Configure&lt;RateLimitOptions&gt;(builder.Configuration.GetSection(&quot;RateLimit&quot;));<br>var app = builder.Build();<br>// Middleware pipeline sırası ÇOK ÖNEMLİ!<br>// 1. Exception handling en başta olmalı<br>app.UseMiddleware&lt;GlobalExceptionHandlingMiddleware&gt;();<br>// 2. Request/Response logging<br>app.UseMiddleware&lt;RequestResponseLoggingMiddleware&gt;();<br>// 3. Rate limiting<br>app.UseMiddleware&lt;RateLimitingMiddleware&gt;();<br>// 4. Authentication<br>app.UseMiddleware&lt;JwtAuthenticationMiddleware&gt;();<br>// 5. Built-in middleware&#39;ler<br>app.UseRouting();<br>app.UseAuthorization();<br>// 6. Endpoints en sonda<br>app.MapControllers();<br>app.Run();</pre><h3>Conditional Middleware</h3><pre>public class ConditionalMiddleware<br>{<br>    private readonly RequestDelegate _next;<br>    <br>    public ConditionalMiddleware(RequestDelegate next)<br>    {<br>        _next = next;<br>    }<br>    <br>    public async Task InvokeAsync(HttpContext context)<br>    {<br>        // Sadece API endpoint&#39;leri için çalış<br>        if (context.Request.Path.StartsWithSegments(&quot;/api&quot;))<br>        {<br>            // API specific işlemler<br>            context.Response.Headers.Add(&quot;X-API-Version&quot;, &quot;1.0&quot;);<br>        }<br>        <br>        await _next(context);<br>    }<br>}<br>// Environment based middleware<br>if (app.Environment.IsDevelopment())<br>{<br>    app.UseMiddleware&lt;DevelopmentMiddleware&gt;();<br>}<br>if (app.Environment.IsProduction())<br>{<br>    app.UseMiddleware&lt;ProductionSecurityMiddleware&gt;();<br>}</pre><h3>Middleware Best Practices</h3><h3>1. Dependency Injection</h3><pre>public class DatabaseMiddleware<br>{<br>    private readonly RequestDelegate _next;<br>    <br>    // Constructor&#39;da sadece RequestDelegate ve singleton service&#39;ler<br>    public DatabaseMiddleware(RequestDelegate next)<br>    {<br>        _next = next;<br>    }<br>    <br>    public async Task InvokeAsync(HttpContext context, IUserService userService, IDbContext dbContext)<br>    {<br>        // Scoped service&#39;leri InvokeAsync&#39;e inject et<br>        <br>        await _next(context);<br>    }<br>}</pre><h3>2. Performance Considerations</h3><pre>public class HighPerformanceMiddleware<br>{<br>    private readonly RequestDelegate _next;<br>    private static readonly ConcurrentDictionary&lt;string, bool&gt; _cache = new();<br>    <br>    public HighPerformanceMiddleware(RequestDelegate next)<br>    {<br>        _next = next;<br>    }<br>    <br>    public async Task InvokeAsync(HttpContext context)<br>    {<br>        // Ağır işlemleri cache&#39;le<br>        var key = context.Request.Path;<br>        var shouldProcess = _cache.GetOrAdd(key, k =&gt; ShouldProcessPath(k));<br>        <br>        if (shouldProcess)<br>        {<br>            // İşlemi yap<br>        }<br>        <br>        await _next(context);<br>    }<br>    <br>    private bool ShouldProcessPath(string path)<br>    {<br>        // Ağır hesaplama<br>        return true;<br>    }<br>}</pre><h3>3. Configuration</h3><pre>public class ConfigurableMiddleware<br>{<br>    private readonly RequestDelegate _next;<br>    private readonly MyMiddlewareOptions _options;<br>    <br>    public ConfigurableMiddleware(RequestDelegate next, IOptions&lt;MyMiddlewareOptions&gt; options)<br>    {<br>        _next = next;<br>        _options = options.Value;<br>    }<br>    <br>    public async Task InvokeAsync(HttpContext context)<br>    {<br>        if (_options.Enabled)<br>        {<br>            // Middleware logic<br>        }<br>        <br>        await _next(context);<br>    }<br>}<br>public class MyMiddlewareOptions<br>{<br>    public bool Enabled { get; set; } = true;<br>    public int TimeoutSeconds { get; set; } = 30;<br>}<br>// Configuration<br>builder.Services.Configure&lt;MyMiddlewareOptions&gt;(<br>    builder.Configuration.GetSection(&quot;MyMiddleware&quot;));</pre><p>Middleware’ler ASP.NET Core’da çok güçlü araçlardır ve doğru kullanıldığında uygulamanızın cross-cutting concern’lerini elegant şekilde çözer.</p><h3>ASP.NET Core Filters ve ActionFilter Attributes</h3><p>Filter’lar, ASP.NET Core’da action method’larının öncesinde ve sonrasında çalışan bileşenlerdir. Cross-cutting concern’leri (authentication, authorization, logging, caching vb.) handle etmek için kullanılır.</p><h3>Filter Pipeline’ı</h3><pre>Request → Authorization → Resource → Action → Result → Exception → Response<br>          ↓              ↓        ↓       ↓        ↓<br>          Filters        Filters  Filters Filters  Filters</pre><h3>Filter Türleri</h3><h3>1. Authorization Filters</h3><p>En önce çalışır, kullanıcının yetkili olup olmadığını kontrol eder.</p><h3>2. Resource Filters</h3><p>Model binding’den önce ve sonra çalışır.</p><h3>3. Action Filters</h3><p>Action method’un öncesi ve sonrasında çalışır.</p><h3>4. Exception Filters</h3><p>Exception handling için kullanılır.</p><h3>5. Result Filters</h3><p>Action result’un execute edilmeden önce ve sonra çalışır.</p><h3>ActionFilter Attribute Oluşturma</h3><h3>Basit ActionFilter</h3><pre>public class LogActionFilter : ActionFilterAttribute<br>{<br>    private readonly ILogger&lt;LogActionFilter&gt; _logger;<br>    <br>    public LogActionFilter(ILogger&lt;LogActionFilter&gt; logger)<br>    {<br>        _logger = logger;<br>    }<br>    <br>    // Action çalışmadan önce<br>    public override void OnActionExecuting(ActionExecutingContext context)<br>    {<br>        var actionName = context.ActionDescriptor.DisplayName;<br>        var controllerName = context.Controller.GetType().Name;<br>        <br>        _logger.LogInformation(&quot;Action {Action} in {Controller} is starting&quot;, <br>            actionName, controllerName);<br>        <br>        // Action parametrelerini logla<br>        foreach (var param in context.ActionArguments)<br>        {<br>            _logger.LogInformation(&quot;Parameter: {Key} = {Value}&quot;, param.Key, param.Value);<br>        }<br>        <br>        base.OnActionExecuting(context);<br>    }<br>    <br>    // Action çalıştıktan sonra<br>    public override void OnActionExecuted(ActionExecutedContext context)<br>    {<br>        var actionName = context.ActionDescriptor.DisplayName;<br>        <br>        if (context.Exception != null)<br>        {<br>            _logger.LogError(context.Exception, &quot;Action {Action} failed&quot;, actionName);<br>        }<br>        else<br>        {<br>            _logger.LogInformation(&quot;Action {Action} completed successfully&quot;, actionName);<br>        }<br>        <br>        base.OnActionExecuted(context);<br>    }<br>}</pre><pre>// Kullanım<br>[ApiController]<br>[Route(&quot;api/[controller]&quot;)]<br>public class UsersController : ControllerBase<br>{<br>    [HttpGet]<br>    [LogActionFilter] // Filter&#39;ı action&#39;a uygula<br>    public async Task&lt;IActionResult&gt; GetUsers()<br>    {<br>        // Action logic<br>        return Ok();<br>    }<br>}</pre><h3>Async ActionFilter</h3><pre>public class AsyncLogActionFilter : IAsyncActionFilter<br>{<br>    private readonly ILogger&lt;AsyncLogActionFilter&gt; _logger;<br>    <br>    public AsyncLogActionFilter(ILogger&lt;AsyncLogActionFilter&gt; logger)<br>    {<br>        _logger = logger;<br>    }<br>    <br>    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)<br>    {<br>        // Action öncesi<br>        var stopwatch = Stopwatch.StartNew();<br>        var actionName = context.ActionDescriptor.DisplayName;<br>        <br>        _logger.LogInformation(&quot;Starting action {Action}&quot;, actionName);<br>        <br>        // Action&#39;ı çalıştır<br>        var resultContext = await next();<br>        <br>        // Action sonrası<br>        stopwatch.Stop();<br>        <br>        if (resultContext.Exception != null)<br>        {<br>            _logger.LogError(resultContext.Exception, <br>                &quot;Action {Action} failed after {Duration}ms&quot;, <br>                actionName, stopwatch.ElapsedMilliseconds);<br>        }<br>        else<br>        {<br>            _logger.LogInformation(&quot;Action {Action} completed in {Duration}ms&quot;, <br>                actionName, stopwatch.ElapsedMilliseconds);<br>        }<br>    }<br>}</pre><h3>Gerçek Dünya Örnekleri</h3><h3>1. Model Validation Filter</h3><pre>public class ValidateModelAttribute : ActionFilterAttribute<br>{<br>    public override void OnActionExecuting(ActionExecutingContext context)<br>    {<br>        if (!context.ModelState.IsValid)<br>        {<br>            var errors = context.ModelState<br>                .SelectMany(x =&gt; x.Value.Errors)<br>                .Select(x =&gt; x.ErrorMessage)<br>                .ToArray();<br>            <br>            var response = new<br>            {<br>                Message = &quot;Validation failed&quot;,<br>                Errors = errors<br>            };<br>            <br>            context.Result = new BadRequestObjectResult(response);<br>            return; // Action çalışmayacak<br>        }<br>        <br>        base.OnActionExecuting(context);<br>    }<br>}</pre><pre>// Kullanım<br>[HttpPost]<br>[ValidateModel]<br>public async Task&lt;IActionResult&gt; CreateUser([FromBody] CreateUserRequest request)<br>{<br>    // Model geçerliyse buraya gelir<br>    return Ok();<br>}</pre><h3>2. Cache Filter</h3><pre>public class CacheAttribute : ActionFilterAttribute<br>{<br>    private readonly int _durationSeconds;<br>    private readonly IMemoryCache _cache;<br>    <br>    public CacheAttribute(int durationSeconds = 300) // 5 dakika default<br>    {<br>        _durationSeconds = durationSeconds;<br>    }<br>    <br>    public override void OnActionExecuting(ActionExecutingContext context)<br>    {<br>        // Cache key oluştur<br>        var cacheKey = GenerateCacheKey(context);<br>        <br>        // ServiceProvider&#39;dan cache service&#39;i al<br>        _cache = context.HttpContext.RequestServices.GetRequiredService&lt;IMemoryCache&gt;();<br>        <br>        if (_cache.TryGetValue(cacheKey, out var cachedResult))<br>        {<br>            // Cache&#39;den döndür<br>            context.Result = (IActionResult)cachedResult;<br>            return; // Action çalışmayacak<br>        }<br>        <br>        // Cache&#39;de yok, action çalışacak<br>        context.HttpContext.Items[&quot;CacheKey&quot;] = cacheKey;<br>        base.OnActionExecuting(context);<br>    }<br>    <br>    public override void OnActionExecuted(ActionExecutedContext context)<br>    {<br>        // Sadece başarılı sonuçları cache&#39;le<br>        if (context.Exception == null &amp;&amp; context.Result is OkObjectResult result)<br>        {<br>            var cacheKey = context.HttpContext.Items[&quot;CacheKey&quot;]?.ToString();<br>            if (!string.IsNullOrEmpty(cacheKey))<br>            {<br>                var options = new MemoryCacheEntryOptions<br>                {<br>                    AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(_durationSeconds),<br>                    Priority = CacheItemPriority.Normal<br>                };<br>                <br>                _cache.Set(cacheKey, context.Result, options);<br>            }<br>        }<br>        <br>        base.OnActionExecuted(context);<br>    }<br>    <br>    private string GenerateCacheKey(ActionExecutingContext context)<br>    {<br>        var keyBuilder = new StringBuilder();<br>        keyBuilder.Append(context.ActionDescriptor.DisplayName);<br>        <br>        // Query parameters<br>        foreach (var param in context.HttpContext.Request.Query.OrderBy(x =&gt; x.Key))<br>        {<br>            keyBuilder.Append($&quot;_{param.Key}:{param.Value}&quot;);<br>        }<br>        <br>        // Action parameters<br>        foreach (var param in context.ActionArguments.OrderBy(x =&gt; x.Key))<br>        {<br>            keyBuilder.Append($&quot;_{param.Key}:{param.Value}&quot;);<br>        }<br>        <br>        return keyBuilder.ToString();<br>    }<br>}</pre><pre>// Kullanım<br>[HttpGet]<br>[Cache(600)] // 10 dakika cache<br>public async Task&lt;IActionResult&gt; GetExpensiveData()<br>{<br>    // Ağır işlem<br>    await Task.Delay(2000);<br>    return Ok(new { Data = &quot;Expensive result&quot; });<br>}</pre><h3>3. Authorization Filter</h3><pre>public class RequirePermissionAttribute : ActionFilterAttribute<br>{<br>    private readonly string _permission;<br>    <br>    public RequirePermissionAttribute(string permission)<br>    {<br>        _permission = permission;<br>    }<br>    <br>    public override void OnActionExecuting(ActionExecutingContext context)<br>    {<br>        var user = context.HttpContext.User;<br>        <br>        if (!user.Identity.IsAuthenticated)<br>        {<br>            context.Result = new UnauthorizedResult();<br>            return;<br>        }<br>        <br>        // Permission kontrolü<br>        var userPermissions = user.FindAll(&quot;permission&quot;).Select(c =&gt; c.Value);<br>        <br>        if (!userPermissions.Contains(_permission))<br>        {<br>            context.Result = new ForbidResult();<br>            return;<br>        }<br>        <br>        base.OnActionExecuting(context);<br>    }<br>}</pre><pre>// Kullanım<br>[HttpDelete(&quot;{id}&quot;)]<br>[RequirePermission(&quot;users:delete&quot;)]<br>public async Task&lt;IActionResult&gt; DeleteUser(int id)<br>{<br>    // Sadece izinli kullanıcılar buraya gelir<br>    return Ok();<br>}</pre><h3>4. Rate Limiting Filter</h3><pre>public class RateLimitAttribute : ActionFilterAttribute<br>{<br>    private readonly int _maxRequests;<br>    private readonly int _windowSeconds;<br>    <br>    public RateLimitAttribute(int maxRequests = 10, int windowSeconds = 60)<br>    {<br>        _maxRequests = maxRequests;<br>        _windowSeconds = windowSeconds;<br>    }<br>    <br>    public override void OnActionExecuting(ActionExecutingContext context)<br>    {<br>        var cache = context.HttpContext.RequestServices.GetRequiredService&lt;IMemoryCache&gt;();<br>        var clientIP = GetClientIP(context.HttpContext);<br>        var actionName = context.ActionDescriptor.DisplayName;<br>        var key = $&quot;ratelimit_{clientIP}_{actionName}&quot;;<br>        <br>        var requests = cache.GetOrCreate(key, entry =&gt;<br>        {<br>            entry.SlidingExpiration = TimeSpan.FromSeconds(_windowSeconds);<br>            return new List&lt;DateTime&gt;();<br>        });<br>        <br>        var now = DateTime.UtcNow;<br>        var windowStart = now.AddSeconds(-_windowSeconds);<br>        <br>        // Eski istekleri temizle<br>        requests.RemoveAll(time =&gt; time &lt; windowStart);<br>        <br>        if (requests.Count &gt;= _maxRequests)<br>        {<br>            context.Result = new ContentResult<br>            {<br>                StatusCode = 429,<br>                Content = &quot;Rate limit exceeded&quot;,<br>                ContentType = &quot;text/plain&quot;<br>            };<br>            <br>            context.HttpContext.Response.Headers.Add(&quot;Retry-After&quot;, _windowSeconds.ToString());<br>            return;<br>        }<br>        <br>        requests.Add(now);<br>        base.OnActionExecuting(context);<br>    }<br>    <br>    private string GetClientIP(HttpContext context)<br>    {<br>        return context.Connection.RemoteIpAddress?.ToString() ?? &quot;unknown&quot;;<br>    }<br>}</pre><pre>// Kullanım<br>[HttpPost(&quot;send-email&quot;)]<br>[RateLimit(5, 300)] // 5 dakikada maksimum 5 istek<br>public async Task&lt;IActionResult&gt; SendEmail([FromBody] EmailRequest request)<br>{<br>    // Email gönderme logic<br>    return Ok();<br>}</pre><h3>5. Performance Monitoring Filter</h3><pre>public class PerformanceMonitorAttribute : ActionFilterAttribute<br>{<br>    private readonly int _warningThresholdMs;<br>    <br>    public PerformanceMonitorAttribute(int warningThresholdMs = 1000)<br>    {<br>        _warningThresholdMs = warningThresholdMs;<br>    }<br>    <br>    public override void OnActionExecuting(ActionExecutingContext context)<br>    {<br>        context.HttpContext.Items[&quot;PerformanceTimer&quot;] = Stopwatch.StartNew();<br>        base.OnActionExecuting(context);<br>    }<br>    <br>    public override void OnActionExecuted(ActionExecutedContext context)<br>    {<br>        if (context.HttpContext.Items[&quot;PerformanceTimer&quot;] is Stopwatch stopwatch)<br>        {<br>            stopwatch.Stop();<br>            var logger = context.HttpContext.RequestServices<br>                .GetRequiredService&lt;ILogger&lt;PerformanceMonitorAttribute&gt;&gt;();<br>            <br>            var actionName = context.ActionDescriptor.DisplayName;<br>            var duration = stopwatch.ElapsedMilliseconds;<br>            <br>            if (duration &gt; _warningThresholdMs)<br>            {<br>                logger.LogWarning(&quot;Slow action detected: {Action} took {Duration}ms&quot;, <br>                    actionName, duration);<br>            }<br>            else<br>            {<br>                logger.LogInformation(&quot;Action {Action} completed in {Duration}ms&quot;, <br>                    actionName, duration);<br>            }<br>            <br>            // Response header&#39;a süre ekle<br>            context.HttpContext.Response.Headers.Add(&quot;X-Response-Time&quot;, duration.ToString());<br>        }<br>        <br>        base.OnActionExecuted(context);<br>    }<br>}</pre><h3>6. Transaction Filter</h3><pre>public class TransactionAttribute : ActionFilterAttribute<br>{<br>    public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)<br>    {<br>        var dbContext = context.HttpContext.RequestServices.GetRequiredService&lt;AppDbContext&gt;();<br>        <br>        using var transaction = await dbContext.Database.BeginTransactionAsync();<br>        <br>        try<br>        {<br>            var result = await next();<br>            <br>            if (result.Exception == null)<br>            {<br>                await transaction.CommitAsync();<br>            }<br>            else<br>            {<br>                await transaction.RollbackAsync();<br>            }<br>        }<br>        catch<br>        {<br>            await transaction.RollbackAsync();<br>            throw;<br>        }<br>    }<br>}</pre><pre>// Kullanım<br>[HttpPost]<br>[Transaction]<br>public async Task&lt;IActionResult&gt; CreateOrderWithItems([FromBody] CreateOrderRequest request)<br>{<br>    // Bu action içindeki tüm DB işlemleri aynı transaction&#39;da çalışır<br>    return Ok();<br>}</pre><h3>Global Filter Registration</h3><pre>// Program.cs<br>builder.Services.AddControllers(options =&gt;<br>{<br>    // Global filter&#39;lar<br>    options.Filters.Add&lt;LogActionFilter&gt;();<br>    options.Filters.Add&lt;ValidateModelAttribute&gt;();<br>    options.Filters.Add(new PerformanceMonitorAttribute(500)); // 500ms threshold<br>});<br>// Scoped service filter<br>builder.Services.AddScoped&lt;CustomActionFilter&gt;();<br>builder.Services.AddControllers(options =&gt;<br>{<br>    options.Filters.Add&lt;CustomActionFilter&gt;();<br>});</pre><h3>Filter Order (Sıralama)</h3><pre>public class HighPriorityFilter : ActionFilterAttribute<br>{<br>    public HighPriorityFilter()<br>    {<br>        Order = 1; // Düşük sayı = yüksek öncelik<br>    }<br>}</pre><pre>public class LowPriorityFilter : ActionFilterAttribute<br>{<br>    public LowPriorityFilter()<br>    {<br>        Order = 10;<br>    }<br>}<br><br><br><br>[HttpGet]<br>[LowPriorityFilter]  // İkinci çalışır<br>[HighPriorityFilter] // Birinci çalışır<br>public IActionResult TestOrder()<br>{<br>    return Ok();<br>}</pre><h3>TypeFilter ve ServiceFilter</h3><pre>// Constructor&#39;da dependency injection gerektiğinde<br>public class DatabaseActionFilter : IActionFilter<br>{<br>    private readonly IUserService _userService;<br>    private readonly ILogger&lt;DatabaseActionFilter&gt; _logger;<br>    <br>    public DatabaseActionFilter(IUserService userService, ILogger&lt;DatabaseActionFilter&gt; logger)<br>    {<br>        _userService = userService;<br>        _logger = logger;<br>    }<br>    <br>    public void OnActionExecuting(ActionExecutingContext context)<br>    {<br>        // Service&#39;leri kullan<br>    }<br>    <br>    public void OnActionExecuted(ActionExecutedContext context)<br>    {<br>        // Service&#39;leri kullan<br>    }<br>}</pre><pre>// Registration<br>builder.Services.AddScoped&lt;DatabaseActionFilter&gt;();<br><br>// Kullanım<br>[HttpGet]<br>[ServiceFilter(typeof(DatabaseActionFilter))] // DI container&#39;dan al<br>public IActionResult GetData()<br>{<br>    return Ok();<br>}<br><br><br>// Veya TypeFilter kullan (her seferinde yeni instance)<br>[HttpGet]<br>[TypeFilter(typeof(DatabaseActionFilter))]<br>public IActionResult GetOtherData()<br>{<br>    return Ok();<br>}</pre><h3>Custom Filter Factory</h3><pre>public class CacheFilterAttribute : Attribute, IFilterFactory<br>{<br>    public int Duration { get; set; }<br>    <br>    public CacheFilterAttribute(int duration = 300)<br>    {<br>        Duration = duration;<br>    }<br>    <br>    public bool IsReusable =&gt; false;<br>    <br>    public IFilterMetadata CreateInstance(IServiceProvider serviceProvider)<br>    {<br>        var cache = serviceProvider.GetRequiredService&lt;IMemoryCache&gt;();<br>        return new CacheActionFilter(cache, Duration);<br>    }<br>}</pre><pre>public class CacheActionFilter : IActionFilter<br>{<br>    private readonly IMemoryCache _cache;<br>    private readonly int _duration;<br>    <br>    public CacheActionFilter(IMemoryCache cache, int duration)<br>    {<br>        _cache = cache;<br>        _duration = duration;<br>    }<br>    <br>    // Filter implementation...<br>}<br><br><br><br>// Kullanım<br>[HttpGet]<br>[CacheFilter(Duration = 600)]<br>public IActionResult GetCachedData()<br>{<br>    return Ok();<br>}</pre><h3>Exception Filter</h3><pre>public class ApiExceptionFilter : ExceptionFilterAttribute<br>{<br>    private readonly ILogger&lt;ApiExceptionFilter&gt; _logger;<br>    <br>    public ApiExceptionFilter(ILogger&lt;ApiExceptionFilter&gt; logger)<br>    {<br>        _logger = logger;<br>    }<br>    <br>    public override void OnException(ExceptionContext context)<br>    {<br>        var exception = context.Exception;<br>        <br>        _logger.LogError(exception, &quot;Unhandled exception in action {Action}&quot;, <br>            context.ActionDescriptor.DisplayName);<br>        <br>        var response = exception switch<br>        {<br>            ValidationException ex =&gt; new { error = &quot;Validation failed&quot;, details = ex.Errors },<br>            NotFoundException ex =&gt; new { error = &quot;Not found&quot;, message = ex.Message },<br>            UnauthorizedAccessException =&gt; new { error = &quot;Unauthorized&quot; },<br>            _ =&gt; new { error = &quot;Internal server error&quot; }<br>        };<br>        <br>        var statusCode = exception switch<br>        {<br>            ValidationException =&gt; 400,<br>            NotFoundException =&gt; 404,<br>            UnauthorizedAccessException =&gt; 401,<br>            _ =&gt; 500<br>        };<br>        <br>        context.Result = new ObjectResult(response) { StatusCode = statusCode };<br>        context.ExceptionHandled = true;<br>    }<br>}</pre><h3>Best Practices</h3><h3>1. Filter vs Middleware Seçimi</h3><pre>// Middleware kullan:<br>// - Tüm request&#39;ler için gerekli<br>// - HTTP context manipülasyonu<br>// - Pipeline&#39;ın erken aşamalarında çalışmalı<br>// Filter kullan:<br>// - Sadece controller/action için gerekli<br>// - Model binding sonrası çalışmalı<br>// - MVC-specific işlemler</pre><h3>2. Performance Considerations</h3><pre>public class OptimizedFilter : ActionFilterAttribute<br>{<br>    private static readonly ConcurrentDictionary&lt;string, bool&gt; _cache = new();<br>    <br>    public override void OnActionExecuting(ActionExecutingContext context)<br>    {<br>        // Ağır işlemleri cache&#39;le<br>        var key = context.ActionDescriptor.DisplayName;<br>        var shouldProcess = _cache.GetOrAdd(key, k =&gt; ShouldProcessAction(k));<br>        <br>        if (shouldProcess)<br>        {<br>            // İşlemi yap<br>        }<br>    }<br>}</pre><h3>3. Testability</h3><pre>public class TestableFilter : ActionFilterAttribute<br>{<br>    private readonly IService _service;<br>    <br>    public TestableFilter(IService service)<br>    {<br>        _service = service;<br>    }<br>    <br>    public override void OnActionExecuting(ActionExecutingContext context)<br>    {<br>        // Service injection sayesinde unit test edilebilir<br>        var result = _service.ProcessData();<br>        context.HttpContext.Items[&quot;ProcessedData&quot;] = result;<br>    }<br>}</pre><pre>// Unit test<br>[Test]<br>public void Filter_ShouldProcessData()<br>{<br>    var mockService = new Mock&lt;IService&gt;();<br>    var filter = new TestableFilter(mockService.Object);<br>    <br>    // Test implementation<br>}</pre><p>Filter’lar, ASP.NET Core’da clean code ve separation of concerns sağlamak için güçlü araçlardır. Doğru kullanıldığında kod tekrarını önler ve maintainability’yi artırır.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73d206ea3108" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>