ASP.NET WebApi实现请求频率限制

SampleController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;

namespace App.Controllers
{
    [Throttle]
    public class SampleController : ApiController
    {
        [HttpGet]
        public async Task<IHttpActionResult> Get() => await Task.FromResult(Ok(Guid.NewGuid().ToString()));
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

ThrottleAttribute.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace App
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class ThrottleAttribute : ActionFilterAttribute
    {
        private readonly HandleRequest _handleRequest;
        public ThrottleAttribute()
        {
            this._handleRequest = new HandleRequest();
        }

        public override async Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
        {
            var valid = await this._handleRequest.IsValidRequest(actionContext.Request);
            if (!valid)
            {
                actionContext.Response = new HttpResponseMessage((HttpStatusCode)429) { ReasonPhrase = "Too Many Requests!" };
            }
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

HandleRequest.cs

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Http;
using System.ServiceModel.Channels;
using System.Threading.Tasks;
using System.Web;
using System.Web.Caching;

namespace App
{
    public class HandleRequest
    {
        private string Name { get; } = "Client1";

        private int Seconds { get; } = int.Parse(ConfigurationManager.AppSettings.Get("waitMillisecond"));


        public async Task<bool> IsValidRequest(HttpRequestMessage requestMessage)
        {
            var allowExecute = false;
            await Task.Factory.StartNew(() =>
            {
                var key = string.Concat(Name, "-", GetClientIp(requestMessage));
                if (HttpRuntime.Cache[key] == null)
                {
                    HttpRuntime.Cache.Add(key,
                        true, //这是我们可以拥有的最小数据吗?
                        null, // 没有依赖关系
                        DateTime.Now.AddMilliseconds(Seconds), // 绝对过期
                        Cache.NoSlidingExpiration,
                        CacheItemPriority.Low,
                        null); //没有回调

                    allowExecute = true;
                }
            });


            return allowExecute;
        }

        private string GetClientIp(HttpRequestMessage request)
        {
            //获取传统context

            if (request.Properties.ContainsKey("MS_HttpContext"))
            { 
                //HttpContextWrapper 类是从 HttpContextBase 类派生的。 HttpContextWrapper 类用作 HttpContext 类的包装。 在运行时,通常使用 HttpContextWrapper 类的实例调用 HttpContext 对象上的成员。
                return ((HttpContextWrapper)request.Properties["MS_HttpContext"]).Request.UserHostAddress;
            }

            //CS客户端获取ip地址
            //让与发送消息的远程终结点有关的客户端 IP 地址和端口号可用。
            if (request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name))
            {
                RemoteEndpointMessageProperty prop;
                prop = (RemoteEndpointMessageProperty)request.Properties[RemoteEndpointMessageProperty.Name];
                return prop.Address;
            }

            return null;
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66

运行结果:

这里写图片描述

1分钟内,连续请求的结果:

这里写图片描述

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值