银天科技设计出品
扫描关注银天科技微信公众账号

广州网站建设

Webapi限制访问频率防止滥用接口

银天科技2019-10-08行业动态
微信公众号开发银天科技的小编,在开发的过程中,需要在webapi中加入控制访问频率,使接口避免不必要的攻击。我们可以这么做。
您在网上搜索到的答案中,可能存在“没有找到合适的方法来重写”的错误,到底是为什么呢?在原答案提供的方法里,有一个错误,现在在这里更正,并且贴出方法。
1、在Nuget中,在WebAPI项目中添加WebApiThrottle的引用。
2、在WebApiConfig的Register方法里添加代码:
(这里可能会找不到CustomThrottlingFilter这个类,需要第三步来解决)

config.Filters.Add(new CustomThrottlingFilter()
            {
                Policy = new ThrottlePolicy()
                {
                    //ip配置区域
                    IpThrottling = true,
                    ClientThrottling = true,
 
                    //端点限制策略配置会从EnableThrottling特性中获取。
                    EndpointThrottling = true
                }
            });
3、新建一个类,重写方法。(这里的类才是正确的)

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()
            };
        }
    }
4、对需要控制的接口或者控制器加上头标示 

 [EnableThrottling(PerMinute = 12)]//控制访问频率,每分钟最多12次
那么,对接口的访问限制,限流,完成了。

微信公众号银天科技,请你点赞!
文章关键词
.net
webapi