webApi限制IP访问接口的频率,OnActionExecuting 停止请求,并优雅的抛出异常。


## asp.net MVC 项目 webAPI 中要想在 过滤去中的 OnActionExecuting 就将请求终止, 

##但是不想用直接粗暴的抛异常的方式。

##如何优雅的抛出我们想要的异常信息呢?


public class IpAccessConFilterAttribute: ActionFilterAttribute
{
 		public long LimitSecond { get; set; } //限制秒数
        public string ApiName { get; set; } //接口名称

    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext) {
        if (!actionContext.ModelState.IsValid)
        {
            var msg = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest,actionContext.ModelState);
            // Now What?
        }
        base.OnActionExecuting(actionContext);
    }
}
public override void OnActionExecuting(HttpActionContext filterContext)
        { 
            var a = LimitSecond;

            string ip  = IPhelp.GetClientIPv4Address();

            string key = ApiName + "_" + ip;

            var v = DataCache.GetCache(key);
            if (v == null)
            {
                DataCache.SetCache(key, ip, DateTime.Now.AddSeconds(LimitSecond), TimeSpan.Zero);
            }
            else
            {
                var response = filterContext.Request.CreateErrorResponse(new InvalidByteRangeException(new ContentRangeHeaderValue(5), $"访问过于频繁!请间隔{LimitSecond.ToString()}秒再次访问!"));
                filterContext.Response = response;
            }

            base.OnActionExecuting(filterContext);
        }

OK,已完成;


版权声明:本文为longyq原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。