如何实现率一个ASP.NET MVC网站的限制? [英] How do I implement rate limiting in an ASP.NET MVC site?

查看:122
本文介绍了如何实现率一个ASP.NET MVC网站的限制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建设,我想限制身份验证的用户如何经常使用该网站的一些功能一个ASP.NET MVC的网站。

I'm building an ASP.NET MVC site where I want to limit how often authenticated users can use some functions of the site.

虽然我知道如何限速作品从根本上,我无法想象如何实现它编程,而无需创建一个主要code气味。

Although I understand how rate-limiting works fundamentally, I can't visualize how to implement it programatically without creating a major code smell.

您可以点我走向了接近这样一个问题一个简单而强大的解决方案,用C#示例code

如果它的事项,所有这些功能目前pssed的动作只接受 HTTP POST 前$ P $。我可能最终要实现限速 HTTP GET 的功能一样,所以我在寻找,对于所有这些情况下的解决方案。

If it matters, all of these functions are currently expressed as Actions that only accept HTTP POST. I may eventually want to implement rate-limiting for HTTP GET functions as well, so I'm looking for a solution that works for all such circumstances.

在此先感谢!

推荐答案

如果您使用的是IIS 7,你可以看看的的动态IP限制扩展。另一种可能性是实现此作为一个动作过滤器:

If you are using IIS 7 you could take a look at the Dynamic IP Restrictions Extension. Another possibility is to implement this as an action filter:

[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;
        }
    }
}

和再装修,需要加以限制的动作:

And then decorate the action that needs to be limited:

[RateLimit(Seconds = 10)]
public ActionResult Index()
{
    return View();
}

这篇关于如何实现率一个ASP.NET MVC网站的限制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆