1、使用Nuget,对WebAPI项目添加WebApiThrottle的引用
2、进行注册,一般是在WebApiConfig的Register方法里添加,代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using WebApiThrottle;
namespace nnn
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API 配置和服务
// Web API 路由
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
//1、使用Nuget,对WebAPI项目添加WebApiThrottle的引用
//2、进行注册,一般是在WebApiConfig的Register方法里添加,代码如下:
config.Filters.Add(new ThrottlingFilter()
{
Policy = new ThrottlePolicy()
{
//ip配置区域
IpThrottling = true,
ClientThrottling = true,
//端点限制策略配置会从EnableThrottling特性中获取。
EndpointThrottling = true
}
});
}
}
}
3、对需要控制的接口或者控制器加上头标示
[EnableThrottling(PerMinute = 12)]//控制访问频率,每分钟最多12次
不需要控制访问频率的可以不加或者加上
[DisableThrotting]
这样就实现了使用过滤器控制特定API的访问频率,更多的使用方法可以参考下面的地址。