嗯,我發現問題是中間件調節器正在處理任何請求到網頁和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);