zhaolei
5 days ago 4a2e5b9a21940f11757be37d99f0944e240e908b
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
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
 
namespace Microsoft.AspNetCore.Mvc.Filters
{
    /// <summary>
    /// IP 地址过滤器
    /// </summary>
    public class IPAddressFilterAttribute : ActionFilterAttribute
    {
        private readonly string _sectionName;
 
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="sectionName">配置项名称</param>
        public IPAddressFilterAttribute(string sectionName)
        {
            _sectionName = sectionName;
        }
 
        /// <summary>
        /// 异步IP地址授权方法
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var config = context.HttpContext.RequestServices.GetRequiredService<IConfiguration>();
            var valid = context.HttpContext.Connection.RemoteIpAddress.ValidateSafeList(config.GetSafeList(_sectionName));
            if (!valid)
            {
                context.Result = new StatusCodeResult(403);
                return;
            }
            base.OnActionExecuting(context);
        }
    }
}