0

我需要在所有操作中使用服务器的 IP。

当我尝试将其放入控制器构造函数中时,它会引发错误:

_runningServer = AppConstants.Common.ServerDetect[Request.ServerVariables["LOCAL_ADDR"].Substring(0, 4)];

我发现的原因是尚未创建 http 上下文。

我尝试使用System.Web.HttpContext.Current,但它没有解决问题。

我在 Intranet 应用程序中使用服务器 IP 作为应用程序以各种方式配置自身的自动方式。

更新:

似乎覆盖 Intialize() 对我的情况来说是一个更好的解决方案:

protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
    base.Initialize(requestContext);
    _runningServer =AppConstants.Common.ServerDetect[System.Web.HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"].Substring(0, 4)];
}
4

3 回答 3

2

您是对的,实例化控制器时 HttpContext 不存在。我会考虑覆盖基本控制器的OnActionExecuting方法并将您的信息存储在那里。

public class MyBaseController : Controller
{
  public string _runningServer;

  protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
      _runningServer = AppConstants.Common.ServerDetect[
        filterContext.HttpContext.Request.ServerVariables.
        ServerVariables["LOCAL_ADDR"].Substring(0, 4)];
        base.OnActionExecuting(filterContext);
    }
}

现在您已经设置了变量,此时 httpContext 可用。_runningServer 变量应该可用于您的所有控制器操作。为了在您的控制器中使用它,您只需要更改类声明。

public class HomeController : MyBaseController
于 2013-10-17T15:13:15.360 回答
1

In alternative to ActionFilter you can Create your own value provider that searches the data in RequestHeaders and populates the IP Address during the model binding.

Check this for Value providers: IValueProvider

于 2013-10-17T15:23:03.970 回答
0

遵循@Tommy 的领导,我在 MSDN 文档中发现该Initialize()方法可能是比以下更好的解决方案OnActionExecuting()

MSDN 链接

初始化调用构造函数时可能不可用的数据。

protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
    base.Initialize(requestContext);
    _runningServer =AppConstants.Common.ServerDetect[System.Web.HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"].Substring(0, 4)];
}
于 2013-10-18T05:36:29.590 回答