zoukankan      html  css  js  c++  java
  • WebApi 限制接口访问频率

    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如下:

        public class CustomThrottlingFilter : ThrottlingFilter
        {
    
            /// <summary>
            /// Sets the indentity.
            /// </summary>
            /// <param name="request">The request.</param>
            /// <returns>RequestIdentity.</returns>
            protected override 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;
                }
                return new RequestIdentity()
                {
                    ClientKey = string.IsNullOrWhiteSpace(sessionId) ? sessionId : "anon",
                    ClientIp = base.GetClientIp(request).ToString(),
                    Endpoint = request.RequestUri.AbsolutePath.ToLowerInvariant()
                };
            }
        }

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

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

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

    [DisableThrotting]

    来源 https://www.cnblogs.com/SzeCheng/p/5407316.html

  • 相关阅读:
    http://localhost:8080/ 演出Oracle说明
    JS浏览器类型推断方法
    MVC设计模式JavaWeb实现
    《TCP/IP详细说明》读书笔记(17章)-TCP传输控制协定
    创建表单
    道路软件质量:SourceMonitor
    HDU
    HDU 3032 Nim or not Nim? (sg函数求解)
    OpenWRT推理client线上的数
    IIS的ISAPI接口简介
  • 原文地址:https://www.cnblogs.com/su-king/p/12167185.html
Copyright © 2011-2022 走看看