专业网站建设品牌,十四年专业建站经验,服务6000+客户--广州京杭网络
免费热线:400-683-0016      微信咨询  |  联系我们

WebApi 限制接口访问频率

当前位置:网站建设 > 技术支持
资料来源:网络整理       时间:2023/2/14 1:11:18       共计:3693 浏览

1、使用Nuget,对WebAPI项目添加WebApiThrottle的引用


2、进行注册,一般是在WebApiConfig的Register方法里添加,代码如下:


config.Filters.Add(new CustomThrottlingFilter()

           {

               Policy = new ThrottlePolicy()

               {

                   //ip配置区域

                   IpThrottling = true,

                   ClientThrottling = true,


                   //端点限制策略配置会从EnableThrottling特性中获取。

                   EndpointThrottling = true

               }

           });


其中CustomThrottlingFilter是自己重写的ThrottlingFilter,也可以直接用默认配置。我自定义的CustomThrottlingFilter如下:


publicclass CustomThrottlingFilter : ThrottlingFilter

   {


       ///<summary>/// Sets the indentity.

       ///</summary>///<param name="request">The request.</param>///<returns>RequestIdentity.</returns>protectedoverride RequestIdentity SetIdentity(HttpRequestMessage request)

       {

           var sessionId = string.Empty;

           try

           {

               var requestCookie = request.Headers.GetCookies().FirstOrDefault();

               if (requestCookie != null)

               {

                   foreach (var item in requestCookie.Cookies.Where(item => item.Name == "Session_Id"))

                   {

                       sessionId = item.Value;

                       break;

                   }

               }

           }

           catch (Exception)

           {

               sessionId = string.Empty;

           }

           returnnew RequestIdentity()

           {

               ClientKey = string.IsNullOrWhiteSpace(sessionId) ? sessionId : "anon",

               ClientIp = base.GetClientIp(request).ToString(),

               Endpoint = request.RequestUri.AbsolutePath.ToLowerInvariant()

           };

       }

   }


3、对需要控制的接口或者控制器加上头标示


[EnableThrottling(PerMinute = 12)]//控制访问频率,每分钟最多12次


不需要控制访问频率的可以不加或者加上


[DisableThrotting]

版权说明:
本网站凡注明“广州京杭 原创”的皆为本站原创文章,如需转载请注明出处!
本网转载皆注明出处,遵循行业规范,如发现作品内容版权或其它问题的,请与我们联系处理!
欢迎扫描右侧微信二维码与我们联系。
·上一条:Solr系列一:Solr(Solr介绍、Solr应用架构、Solr安装使用) | ·下一条:C# 仿刷-框架MvcThrottle的使用

Copyright © 广州京杭网络科技有限公司 2005-2025 版权所有    粤ICP备16019765号 

广州京杭网络科技有限公司 版权所有