public MessageHandlerTrottle() { this._throttlingHandler = new ThrottlingHandler() { Policy = ThrottlePolicy.FromStore(new PolicyConfigurationProvider()), Repository = new CacheRepository() }; }
private HttpClient CreateClient() { HttpMessageHandler handler = new HttpClientHandler(); handler = new LoggingMessageHandler(handler, this.log, this.timeProvider, this.repository); handler = new ThrottlingHandler(handler, this.settings); return(new HttpClient(handler)); }
private async Task <DataResponseModel> GetDataFromEndpoint() { HttpResponseMessage response; // the number of parallel request that can be made to the data endpoint. int maxParallelism = Convert.ToInt16(_config["maxParallelism"]); var dataResponse = new DataResponseModel(); // The number of days the response from the data endpoint int timeToLiveSeconds = Convert.ToInt32(_config["DataUrlTimeToLive"]); var cachedResponse = await _iResponseCacheService.GetCachedResponseAsync(_dataUrl); if (string.IsNullOrEmpty(cachedResponse)) { // The handler for the number of requests var handler = new ThrottlingHandler(new SemaphoreSlim(maxParallelism), new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate, }); using (var client = new HttpClient(handler)) { client.Timeout = Timeout; response = await client.GetAsync(_dataUrl); // This checks if the request was successfull or times out. if (response.IsSuccessStatusCode) { cachedResponse = response.Content.ReadAsStringAsync().Result; dataResponse = JsonConvert.DeserializeObject <DataResponseModel>( cachedResponse, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto } ); await _iResponseCacheService.CacheResponseAsync(_dataUrl, dataResponse, TimeSpan.FromSeconds(timeToLiveSeconds)); return(dataResponse); } else { throw new CustomResponseException("Endpoint Could not be reached."); } } } else { return(JsonConvert.DeserializeObject <DataResponseModel>( cachedResponse, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto } )); } }
public static void Register(HttpConfiguration config) { // Web API configuration and services //config.AddApiVersioning(o => o.AssumeDefaultVersionWhenUnspecified = true); //GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerSelector), new VersionHttpControllerSelector(GlobalConfiguration.Configuration)); // added to the web api configuration in the application setup config.MapHttpAttributeRoutes(); // Configure Web API to use only bearer token authentication. //config.SuppressDefaultHostAuthentication(); //config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); config.Filters.Add(new CustomErrorAttribute()); #if DEBUG var traceWriter = config.EnableSystemDiagnosticsTracing(); traceWriter.IsVerbose = true; traceWriter.MinimumLevel = TraceLevel.Debug; #endif // Web API routes //config.MapHttpAttributeRoutes(); //var r=config.Routes.MapHttpRoute( // name: "v2API", // routeTemplate: "api/v{version}/{controller}/{id}", // defaults: new // { // id = RouteParameter.Optional, // } //); //r.Constraints.Add("version", "([0-9]{1,2})|([0-9]{1,2}.[0-9]{0,2})"); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); ////https://github.com/stefanprodan/WebApiThrottle //var throttlingHandler = new ThrottlingHandler() //{ // Policy = new ThrottlePolicy(perSecond: 20, perMinute: 300)//, perHour: 36000, perDay: 864000, perWeek: 6048000) // { // //scope to IPs // IpThrottling = true, // //IpRules = new Dictionary<string, RateLimits> // //{ // // {"::1/10", new RateLimits {PerSecond = 2}}, // // {"192.168.2.1", new RateLimits {PerMinute = 30, PerHour = 30*60, PerDay = 30*60*24}} // //}, // //white list the "::1" IP to disable throttling on localhost for Win8 // //IpWhitelist = new List<string> (Config.IpThrottlingWhiteList), // //scope to clients (if IP throttling is applied then the scope becomes a combination of IP and client key) // //ClientThrottling = true, // //ClientRules = new Dictionary<string, RateLimits> // //{ // // {"api-client-key-1", new RateLimits {PerMinute = 60, PerHour = 600}}, // // {"api-client-key-9", new RateLimits {PerDay = 5000}} // //}, // //white list API keys that don’t require throttling // //ClientWhitelist = new List<string> {"admin-key"}, // //scope to routes (IP + Client Key + Request URL) // EndpointThrottling = true, // EndpointRules = new Dictionary<string, RateLimits> // { // //per hour per client IP // {"api/Feedback/", new RateLimits {PerHour = 20}}, // {"api/Restrooms/", new RateLimits {PerHour = 2000}}, // {"api/Operator/", new RateLimits {PerHour = 500}}, // {"api/v2/Feedback/", new RateLimits {PerHour = 20}}, // twenty feedbacks per hour per client IP // {"api/v2/Restrooms/", new RateLimits {PerHour = 2000}}, // Restrooms per hour per client IP // {"api/v2/Operator/", new RateLimits {PerHour = 2000}}, // {"api/v2/Authentication", new RateLimits {PerHour = 50}}, // {"api/v2/Authentication/send", new RateLimits {PerHour = 5}}, // {"api/Version/", new RateLimits {PerHour = 500}}, // } // }, // Repository = new CacheRepository(), //}; #if DEBUG var throttlingHandler = new ThrottlingHandler(); throttlingHandler.Logger = new TracingThrottleLogger(traceWriter); #endif //config.MessageHandlers.Add(throttlingHandler); config.MessageHandlers.Add(new ThrottlingHandler() { Policy = ThrottlePolicy.FromStore(new PolicyConfigurationProvider()), Repository = new CacheRepository() }); }
public static void Register(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("HttpConfiguration is null."); } config.Services.Add(typeof(IExceptionLogger), new GlobalExceptionLogger()); config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler()); // Web API configuration and services #if DEBUG var traceWriter = config.EnableSystemDiagnosticsTracing(); traceWriter.IsVerbose = true; traceWriter.MinimumLevel = TraceLevel.Debug; #endif // enable Cross Origin Resource Sharing (CORS) var cors = new EnableCorsAttribute("*", "*", "*") // TODO: change to your.company.dns/path/to/CusRel Website { SupportsCredentials = true }; config.EnableCors(cors); // Configure Web API to use only bearer token authentication. config.SuppressDefaultHostAuthentication(); config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); // add XML and JSON formatters for requests and responses config.Formatters.XmlFormatter.AddUriPathExtensionMapping("xml", XmlMediaTypeFormatter.DefaultMediaType); config.Formatters.JsonFormatter.AddUriPathExtensionMapping("json", JsonMediaTypeFormatter.DefaultMediaType); // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultActionIdApi", routeTemplate: "{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Routes.MapHttpRoute( name: "DefaultActionIdKeyApi", routeTemplate: "{controller}/{action}/{id}/{key}" ); config.Routes.MapHttpRoute( name: "DefaultIdActionApi", routeTemplate: "{controller}/{id}/{action}", defaults: new { id = RouteParameter.Optional } ); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); //Web API throttling var throttlingHandler = new ThrottlingHandler() { Policy = new ThrottlePolicy(perSecond: 20, perMinute: 300)//, perHour: 36000, perDay: 864000, perWeek: 6048000) { //scope to IPs IpThrottling = true, //IpRules = new Dictionary<string, RateLimits> //{ // {"::1/10", new RateLimits {PerSecond = 2}}, // {"192.168.2.1", new RateLimits {PerMinute = 30, PerHour = 30*60, PerDay = 30*60*24}} //}, //white list the "::1" IP to disable throttling on localhost for Win8 IpWhitelist = new List <string> { "::1", "127.0.0.1", "192.168.0.0/16", "10.0.0.0/8", "172.16.0.0/12" }, //scope to clients (if IP throttling is applied then the scope becomes a combination of IP and client key) //ClientThrottling = true, //ClientRules = new Dictionary<string, RateLimits> //{ // {"api-client-key-1", new RateLimits {PerMinute = 60, PerHour = 600}}, // {"api-client-key-9", new RateLimits {PerDay = 5000}} //}, //white list API keys that don’t require throttling //ClientWhitelist = new List<string> {"admin-key"}, //scope to routes (IP + Client Key + Request URL) EndpointThrottling = true, EndpointRules = new Dictionary <string, RateLimits> { { "feedback/", new RateLimits { PerHour = 2 } }, // two feedback per hour per client IP } }, Repository = new CacheRepository(), }; #if DEBUG throttlingHandler.Logger = new TracingThrottleLogger(traceWriter); #endif config.MessageHandlers.Add(throttlingHandler); }