0

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 = "" });
            }
        }
    }
}
4

1 回答 1

3

在我看来,在基本构造函数中重定向还为时过早。在控制器初始化期间,您的 HttpContext 似乎为空,因此您可能会收到一个空引用异常。

我会寻找一种不同的方法,例如创建一个 ActionFilter。并在您需要的任何地方使用它。您可以注册为全局过滤器或控制器级别等。类似这样的东西。

    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()
         {            
         }
    }
于 2013-10-26T22:29:38.337 回答