Last active
June 25, 2021 07:02
-
-
Save tocalai/a5109dc9916042b09ddbc7d072f417fe to your computer and use it in GitHub Desktop.
Mock class for demonstrate apply cache policy for controlling duplicated request.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// supposed we have class to monitor request | |
public class RequestMonitor { | |
private readonly Context _context; | |
private readonly IMemoryCache _cache; | |
public RequestMonitor (Context context, IMemoryCache cache) { | |
_context = context; // DI the context of Http request | |
_cache = cache; | |
} | |
public void OnRequested () { | |
// retrieved http request information | |
var hostName = _context.GetHttpContext ().Request.Host.Value; | |
var hostAddress = _context.GetHttpContext ().Request.HttpContext.Connection.RemoteIpAddress; | |
var keys = _context.GetHttpContext ().Request.Headers.Keys; | |
var host = _context.GetHttpContext ().Request.Headers["Host"]; | |
var userAgent = _context.GetHttpContext ().Request.Headers["User-Agent"]; | |
var realIP = _context.GetHttpContext ().Request.Headers["X-Real-IP"]; | |
var forwardeds = _context.GetHttpContext ().Request.Headers["X-Forwarded-For"]; | |
var connectedInfo = new Dictionary<string, string> () { { "HostAddress", hostAddress.ToString () }, { "Host", host }, { "UserAgent", userAgent }, { "Real-IP", realIP }, { "Forward-For", forwardeds }, | |
}; | |
var key = string.Concat(hostAddress, "|", realIP.ToString()); | |
var isExisted = _cache.TryGetValue(key, out var entry); | |
// place further action logic for the request | |
// check if belongs to black list.. | |
// ... | |
if (isExisted) return; | |
Console.WriteLine("----------------------------------------------->"); | |
Console.WriteLine($"{DateTime.UtcNow:yyyy/MM/dd HH:mm:ss}, [Info]: {JsonConvert.SerializeObject(connectedInfo)}"); | |
Console.WriteLine("<-----------------------------------------------"); | |
// add to cache with expired time (20 secs) | |
var cacheEntryOptions = new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromSeconds(20)); | |
_cache.Set(key, connectedInfo, cacheEntryOptions); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment