当前位置:   article > 正文

Asp .Net Core Web API Rate Limit_aspnetcoreratelimit如实现clientid自定义

aspnetcoreratelimit如实现clientid自定义

原文参考:

https://github.com/stefanprodan/AspNetCoreRateLimit(Code)

https://github.com/stefanprodan/AspNetCoreRateLimit/wiki (Wiki)

https://www.getpostman.com/(Http Tool)

解决思路:

Http请求时,通过Header传值(X-ClientId)判断并计数指定接口的调用次数,从而拦截超过设置上限的调用请求。其中,X-ClientId为自定义参数。

参数配置(appsettings.json e.g):

"ClientRateLimiting": {
		"EnableEndpointRateLimiting": true,
		"StackBlockedRequests": false,
		"ClientIdHeader": "X-ClientId",
		"HttpStatusCode": 429,
		"EndpointWhitelist": [],
		"ClientWhitelist": [],
		"GeneralRules": [
			{
				"Endpoint": "get:/api/services/app/CountActivity/GetCountActivity",
				"Period": "1s",
				"Limit": 1
			}
		]
	}

服务配置(Startup.cs e.g):

  1. public IServiceProvider ConfigureServices(IServiceCollection services)
  2. {
  3. services.AddOptions();
  4. services.Configure<ClientRateLimitOptions>(_appConfiguration.GetSection("ClientRateLimiting"));
  5. // inject counter and rules stores
  6. services.AddSingleton<IClientPolicyStore, DistributedCacheClientPolicyStore>();
  7. services.AddSingleton<IRateLimitCounterStore, DistributedCacheRateLimitCounterStore>();
  8. }
  1. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
  2. {
  3. app.UseClientRateLimiting();
  4. app.UseMvc();
  5. }

方法重写:

对于拦截过滤有自定义需求时,可以重写ClientRateLimitMiddleware.SetIdentity方法实现

  1. public virtual ClientRequestIdentity SetIdentity(HttpContext httpContext)
  2. {
  3. var clientId = "anon";
  4. if (httpContext.Request.Headers.Keys.Contains(_options.ClientIdHeader,StringComparer.CurrentCultureIgnoreCase))
  5. {
  6. clientId = httpContext.Request.Headers[_options.ClientIdHeader].First();
  7. }
  8. return new ClientRequestIdentity
  9. {
  10. Path = httpContext.Request.Path.ToString().ToLowerInvariant(),
  11. HttpVerb = httpContext.Request.Method.ToLowerInvariant(),
  12. ClientId = clientId
  13. };
  14. }


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/788444
推荐阅读
相关标签
  

闽ICP备14008679号