최고의 방법으로 구현하는 요청을 제한에 ASP.NET MVC?
-
09-06-2019 - |
문제
우리는 실험으로 다양한 방법으로 제한하는 사용자 작업에서 주어진 시간:
- 제한 질문/답변 게시물
- 제한 편집
- 제한 피드 검색
간,우리가 사용하여 캐시을 간단히 삽입하는 기록 사용자 활동의 경우 기록이 존재하는 경우 사용자가 같은 활동,우리는 스로틀.
캐시를 사용하여 자동으로 우리에게 오래된 데이터 클리닝 및 슬라이딩 활동의 창의 사용자가,하지만 어떻게 그것이 스케일 문제가 될 수 있습니다.
어떤 것이 있는 다른 방법으로 손님들의 요청을 사용자 작업을 할 수 있습니다 효과적으로 제한(에 중점을 안정성)?
해결책
여기에 일반 버전에 우리가 사용하여 스택에서 오버플로 지난 해:
/// <summary>
/// Decorates any MVC route that needs to have client requests limited by time.
/// </summary>
/// <remarks>
/// Uses the current System.Web.Caching.Cache to store each client request to the decorated route.
/// </remarks>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class ThrottleAttribute : ActionFilterAttribute
{
/// <summary>
/// A unique name for this Throttle.
/// </summary>
/// <remarks>
/// We'll be inserting a Cache record based on this name and client IP, e.g. "Name-192.168.0.1"
/// </remarks>
public string Name { get; set; }
/// <summary>
/// The number of seconds clients must wait before executing this decorated route again.
/// </summary>
public int Seconds { get; set; }
/// <summary>
/// A text message that will be sent to the client upon throttling. You can include the token {n} to
/// show this.Seconds in the message, e.g. "Wait {n} seconds before trying again".
/// </summary>
public string Message { get; set; }
public override void OnActionExecuting(ActionExecutingContext c)
{
var key = string.Concat(Name, "-", c.HttpContext.Request.UserHostAddress);
var allowExecute = false;
if (HttpRuntime.Cache[key] == null)
{
HttpRuntime.Cache.Add(key,
true, // is this the smallest data we can have?
null, // no dependencies
DateTime.Now.AddSeconds(Seconds), // absolute expiration
Cache.NoSlidingExpiration,
CacheItemPriority.Low,
null); // no callback
allowExecute = true;
}
if (!allowExecute)
{
if (String.IsNullOrEmpty(Message))
Message = "You may only perform this action every {n} seconds.";
c.Result = new ContentResult { Content = Message.Replace("{n}", Seconds.ToString()) };
// see 409 - http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
c.HttpContext.Response.StatusCode = (int)HttpStatusCode.Conflict;
}
}
}
샘플 사용:
[Throttle(Name="TestThrottle", Message = "You must wait {n} seconds before accessing this url again.", Seconds = 5)]
public ActionResult TestThrottle()
{
return Content("TestThrottle executed");
}
이 ASP.NET 캐시 작품 챔피언처럼 여기를 사용하여-그것은,당신은 자동적인 정의 스로틀 항목이 있습니다.와 우리의 성장하고 트래픽을,우리는 우리가 보이지 않는 것이 문제는 서버에 있습니다.
료에 대한 피드백을 제공하기 위해 이 방법;때 우리는 Stack Overflow 더 나은,당신은 당신의 감을 해결 더욱 빠르다:)
다른 팁
Microsoft 는 새로운 확장자를 위한 IIS7 동적 IP 주소라는 제한에 대한 확장 IIS7.0-베타 버전입니다.
"동적 IP 에 대한 제한이 IIS7.0 이 제공하는 모듈에 대한 보호 서비스 거부하고 무력을 공격에 웹 서버와 웹 사이트입니다.이러한 보호는 제공을 일시적으로 차단하는 IP 주소를 사용한 HTTP 클라이언트가 만들의 비정상적으로 높은 숫자를 동시에 요청이나 사람들의 큰 숫자를 요청을 통해 작은 기간 동안의 시간입니다." http://learn.iis.net/page.aspx/548/using-dynamic-ip-restrictions/
예제:
는 경우에 당신은 기준을 설정하면 차단 X requests in Y milliseconds
나 X concurrent connections in Y milliseconds
IP 주소를 차단됩 Y milliseconds
다음 요청하는 것이 허용될 것이 다시합니다.
우리가 사용하는 기법에서 빌린이 URL http://www.codeproject.com/KB/aspnet/10ASPNetPerformance.aspx, 지에 대한 제한,그러나 가난한 사람의 서비스 거부(D.O.S).이것은 또한 캐시 기반 및 유사할 수 있습니다 무엇을하고있다.당신은 제한을 방지하 D.O.S.공격?라우터지 않을 것임을 확신하게 될 것을 줄이기 위해 사용 D.O.S;당신이 생각하는 라우터 처리할 수 있는 제한을 필요로 하는가?