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