yuanhung
2024-02-05 876ccb53468872e1156a9f93d4cb72af7fb49c8e
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
67
68
69
70
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
 
namespace MailQuery.Filter 
{
    public class AllowedIPAttribute :  System.Web.Mvc.ActionFilterAttribute,IActionFilter // System.Web.Mvc.ActionFilterAttribute
    {
         void IActionFilter.OnActionExecuted(System.Web.Mvc.ActionExecutedContext filterContext){
 
            string userIPAddress = HttpContext.Current.Request.UserHostAddress;
            if (!checkInAllowIP(userIPAddress))
            {
                filterContext.Result = new HttpStatusCodeResult(404);
            }
            OnActionExecuted(filterContext);
        }
 
        void IActionFilter.OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext)
        {
            string userIPAddress = HttpContext.Current.Request.UserHostAddress;
            if (!checkInAllowIP(userIPAddress))
            {
                filterContext.Result = new HttpStatusCodeResult(404);
            }
            OnActionExecuting(filterContext);
        }
        private bool checkInAllowIP(string ip)
        {
            bool bPass = false;
            if (ip.Equals("::1")|ip.Equals("127.0.0.1"))
            {
                bPass= true;
                return bPass;
            }
 
            using (developEntities entities = new developEntities())
            {
                var allowSource = (from lst602_9 in entities.SysEnvVar
                                   where lst602_9.CodeID > 601 && lst602_9.CodeID < 610
                                   select lst602_9.CodeValue).ToList();
                if (allowSource.Count == 0) { bPass = false; }
                else
                {
                    List<string> lstIP = new List<string>();
                    foreach (string ipa in allowSource)
                    {
                        lstIP.AddRange(ipa.Split(new char[] { ',' }));
                    }
                    lstIP.RemoveAll(x => x == "");
                    if (!String.IsNullOrEmpty(ip))
                    {
                        //if (ip.Equals("::1")) ip = "127.0.0.1";
                        if (lstIP.Contains(ip))
                        {
                            bPass = true; //accept
                        }
                        
                    }
 
                }
            }
 
            return bPass;
        }
    }
}