關於限流的文章,博客園內仍是有挺多的。本文作了一個基於Filter限流的例子,算是對WebApiThrottle使用的一個具體的實例。html
一、使用Nuget,對WebAPI項目添加WebApiThrottle的引用session
二、進行註冊,通常是在WebApiConfig的Register方法裏添加,代碼以下:框架
1 config.Filters.Add(new CustomThrottlingFilter() 2 { 3 Policy = new ThrottlePolicy() 4 { 5 //ip配置區域 6 IpThrottling = true, 7 ClientThrottling = true, 8 9 //端點限制策略配置會從EnableThrottling特性中獲取。 10 EndpointThrottling = true 11 } 12 });
其中CustomThrottlingFilter是本身重寫的ThrottlingFilter,也能夠直接用默認配置。我自定義的CustomThrottlingFilter以下:ide
1 public class CustomThrottlingFilter: ThrottlingFilter 2 { 3 /// <summary> 4 /// Sets the indentity. 5 /// </summary> 6 /// <param name="request">The request.</param> 7 /// <returns>RequestIdentity.</returns> 8 protected override RequestIdentity SetIndentity(HttpRequestMessage request) 9 { 10 var sessionId = string.Empty; 11 try 12 { 13 var requestCookie = request.Headers.GetCookies().FirstOrDefault(); 14 if (requestCookie != null) 15 { 16 foreach (var item in requestCookie.Cookies.Where(item => item.Name == "Session_Id")) 17 { 18 sessionId = item.Value; 19 break; 20 } 21 } 22 } 23 catch (Exception) 24 { 25 sessionId = string.Empty; 26 } 27 return new RequestIdentity() 28 { 29 ClientKey = string.IsNullOrWhiteSpace(sessionId) ? sessionId : "anon", 30 ClientIp = base.GetClientIp(request).ToString(), 31 Endpoint = request.RequestUri.AbsolutePath.ToLowerInvariant() 32 }; 33 } 34 }
三、對須要控制的接口或者控制器加上頭標示 post
[EnableThrottling(PerMinute = 12)]//控制訪問頻率,每分鐘最多12次
不須要控制訪問頻率的能夠不加或者加上url
[DisableThrotting]
這樣就實現了使用過濾器控制特定API的訪問頻率,更多的使用方法能夠參考下面的地址。spa
參考資料:code
WebApiThrottle限流框架使用手冊 http://www.cnblogs.com/mushroom/p/4659200.htmlhtm
控制ASP.NET Web API 調用頻率與限流 http://www.cnblogs.com/Irving/p/4664786.htmlblog