嗯,我发现问题是中间件调节器正在处理任何请求到网页和MVC调节器也处理任何请求到网页。每个调节器都在读取和写入同一个缓存,但是当他们从缓存中读取值时,会试图将该对象转换为WebApiThrottle对象,另一个试图将该对象转换为MvcThrottle对象。那不好。
所以我通过给中间件节制自己精心构造的策略来解决这个问题。默认情况下,策略不限制任何内容。然后,我添加一条规则来专门将安全限制应用于安全令牌端点。
这样安全令牌端点仍然受速率限制,但网页调速完全由MVC调速属性处理。中间件调节器将忽略其规则列表中未覆盖的任何内容,因为默认速率限制全部为0,这意味着不进行限制。例外消失,一切都很好。
这里是中间件限制策略类的样子:
public class MiddlewareThrottlingPolicy : ThrottlePolicy
{
/// <summary>
/// Creates the middleware throttling policy
/// </summary>
public MiddlewareThrottlingPolicy()
{
//Everything is unthrottled by default. We don't have to do anything to achieve that
//We're throttling by endpoint
EndpointThrottling = true;
//Add the endpoints that get different throttling
RateLimits policySettings = new RateLimits
{
PerSecond = 30,
PerMinute = 100,
PerHour = 200,
PerDay = 500,
PerWeek = 0
};
EndpointRules = new Dictionary<string, RateLimits>
{
{ "/api/authentication/token", policySettings }
};
}
}
在实际应用中,我从加载配置设置的速率限制,但我在这里简化它。
下面是如何应用中间件限制策略启动应用程序时:
app.Use(typeof(ThrottlingMiddleware),
new MiddlewareThrottlingPolicy(),
new PolicyCacheRepository(),
new CacheRepository(),
null,
null);