我正在尝试通过以下方式实施请求限制:
我已将该代码放入解决方案中,并使用属性装饰了API控制器端点:
[Route("api/dothis/{id}")]
[AcceptVerbs("POST")]
[Throttle(Name = "TestThrottle", Message = "You must wait {n} seconds before accessing this url again.", Seconds = 5)]
[Authorize]
public HttpResponseMessage DoThis(int id) {...}
这样可以编译,但是属性的代码未命中,并且节流也不起作用。我没有任何错误。我想念什么?
您似乎对ASP.NET MVC控制器的动作过滤器和ASP.NET Web API控制器的动作过滤器感到困惑。这是2个完全不同的类:
System.Web.Mvc.ActionFilterAttribute
->这就是您从链接中获得的内容System.Web.Http.Filters.ActionFilterAttribute
->这就是您需要实现的您似乎看到的是Web API控制器操作(在衍生自的控制器内部声明的操作ApiController
)。因此,如果您要对其应用自定义过滤器,则它们必须从派生System.Web.Http.Filters.ActionFilterAttribute
。
因此,让我们继续为Web API修改代码:
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(HttpActionContext actionContext)
{
var key = string.Concat(Name, "-", GetClientIp(actionContext.Request));
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.";
}
actionContext.Response = actionContext.Request.CreateResponse(
HttpStatusCode.Conflict,
Message.Replace("{n}", Seconds.ToString())
);
}
}
}
其中GetClientIp
方法来自this post
。
现在,您可以在Web API控制器操作上使用此属性。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句