17

認証されたユーザーがサイトの一部の機能を使用できる頻度を制限したい ASP.NET MVC サイトを構築しています。

レート制限が基本的にどのように機能するかは理解していますが、主要なコードの臭いを発生させずにプログラムで実装する方法を視覚化することはできません。

C# のサンプル コードを使用して、このような問題に対処するためのシンプルかつ強力なソリューションを教えてください。

問題があれば、現在、これらの機能はすべて、 のみを受け入れるアクションとして表現されていますHTTP POST。最終的には関数にもレート制限を実装したいと思うかもしれないHTTP GETので、そのようなすべての状況で機能するソリューションを探しています。

4

2 に答える 2

28

IIS 7 を使用している場合は、Dynamic IP Restrictions Extensionを参照してください。もう 1 つの可能性は、これをアクション フィルターとして実装することです。

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class RateLimitAttribute : ActionFilterAttribute
{
    public int Seconds { get; set; }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Using the IP Address here as part of the key but you could modify
        // and use the username if you are going to limit only authenticated users
        // filterContext.HttpContext.User.Identity.Name
        var key = string.Format("{0}-{1}-{2}",
            filterContext.ActionDescriptor.ControllerDescriptor.ControllerName,
            filterContext.ActionDescriptor.ActionName,
            filterContext.HttpContext.Request.UserHostAddress
        );
        var allowExecute = false;

        if (HttpRuntime.Cache[key] == null)
        {
            HttpRuntime.Cache.Add(key,
                true,
                null,
                DateTime.Now.AddSeconds(Seconds),
                Cache.NoSlidingExpiration,
                CacheItemPriority.Low,
                null);
            allowExecute = true;
        }

        if (!allowExecute)
        {
            filterContext.Result = new ContentResult
            {
                Content = string.Format("You can call this every {0} seconds", Seconds)
            };
            filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Conflict;
        }
    }
}

そして、制限する必要があるアクションを装飾します。

[RateLimit(Seconds = 10)]
public ActionResult Index()
{
    return View();
}
于 2010-06-21T07:48:09.030 に答える
4

SOでこれを行う方法についてのJarrodの回答をご覧ください。

StackOverflow MVC スロットリング

いくつかのサンプルコードと、それがどのように機能するかについての説明。

于 2010-06-21T10:56:09.623 に答える