Matthew Verstraete
Matthew Verstraete

Reputation: 6781

Get User IP in a BaseController?

I am making a base controller that my other controllers will inherit from and one of the things I want to do is grab the user's IP Address and check it see if it is the one I want, if it is not I want to redirect them to the home page. I tested the code in a normal controller and it works fine but as soon as I move the code to BaseController it errors with a Null Reference Exception. How can I get this to work in my Base Controller?

using FFInfo.WebUI.Controllers;
using System.Web.Mvc;

namespace FFInfo.WebUI.Areas.Admin.Controllers
{
    public class AdminBaseController : GlobalBaseController
    {
        public AdminBaseController()
        {
            if (HttpContext.Request.ServerVariables["REMOTE_HOST"] != "ValidIP")
            {
                RedirectToAction("Index", "Home", new { area = "" });
            }
        }
    }
}

Upvotes: 0

Views: 665

Answers (1)

Spock
Spock

Reputation: 6992

It looks to me that it is too early to redirect within a base constructor. Your HttpContext seems null during the Controller initialization therefore you probably be getting a null ref exception.

I would look for a different approach for example creating an ActionFilter. And use it where ever you need. You can register as a Global Filter or as a Controller level etc. Something like this.

    public class IpCheckFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext) {
        if (filterContext.HttpContext.Request.ServerVariables["REMOTE_HOST"] != "ValidIP")
        {
            filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary { { "controller", "Home" }, { "action", "Index" } });
        }
    }

    [IpCheckFilter]
    public class HomeController : AdminBaseController
    {
         public HomeController() : base()
         {            
         }
    }

Upvotes: 3

Related Questions