.Net Asp.Net MVC Development

Creating IP based Access Validation

First you have to create a validation class which will do the work.

public class AuthorizeIPAddressAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            string ipAddress = HttpContext.Current.Request.UserHostAddress;
            
            if (!IsIpAddressAllowed(ipAddress.Trim()))
            {
                using (OPIEntities OPIdb = new OPIEntities())
                {
                    activity act = new activity();
                    act.activityuser = "user";
                    act.message = "Unauthorised IP Host Address: "+ipAddress+" for "+HttpContext.Current.Request.Url;
                    act.type = "actype";
                    act.activitytime = DateTime.Now.AddHours(4);
                    act.IpAddress = ipAddress;
                    OPIdb.activities.Add(act);
                    OPIdb.SaveChanges();
                }
                    context.Result = new HttpStatusCodeResult(403);
            }
            base.OnActionExecuting(context);
        }

        private bool IsIpAddressAllowed(string IpAddress)
        {
            if (!string.IsNullOrWhiteSpace(IpAddress))
            {
                string[] addresses = Convert.ToString(ConfigurationManager.AppSettings["AllowedIPAddresses"]).Split(',');
                return addresses.Where(a => a.Trim().Equals(IpAddress, StringComparison.InvariantCultureIgnoreCase)).Any();
            }
            return false;
        }
    }

Once that is done, now you can use the attributes in your controllers and actions like this:

[AuthorizeIPAddress]
public class HomeController : Controller  {}
or
[AuthorizeIPAddress]
public ActionResult Index()

Leave a Reply

Your email address will not be published. Required fields are marked *