【问题标题】:an object reference is required for non static method or property 'System.Web.MVC.ControllerContext.Controller.get'非静态方法或属性“System.Web.MVC.ControllerContext.Controller.get”需要对象引用
【发布时间】:2011-10-06 17:58:14
【问题描述】:

我在我的 asp.net MVC 3 应用程序的 Model 文件夹中创建了一个类,并在其中使用了以下代码

   var controller = ViewContext.Controller.ValueProvider.GetValue("controller").RawValue

但它带有下划线并表示:非静态方法或属性需要对象引用

'System.Web.MVC.ControllerContext.Controller.get'

如何摆脱这个错误。

以下是完整代码:

public void OnAuthorization(AuthorizationContext filterContext)
        {
            var user = (CreditRegistryPrincipal)filterContext.HttpContext.User;
            if (!user.IsAdminAuthorized)
            {
                var controller = System.Web.Mvc.ControllerContext ViewContext.Controller.ValueProvider.GetValue("controller").RawValue;

                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { 
                    { "controller", "Admin" }, 
                    { "action", "adfdsf" } 
                });
            }
        }

问候, 阿西夫

【问题讨论】:

  • 你在用 var 控制器做什么?看起来您从未在其余代码中的任何地方使用过它...

标签: asp.net-mvc asp.net-mvc-3


【解决方案1】:

这一行:

var controller = System.Web.Mvc.ControllerContext ViewContext.Controller.ValueProvider.GetValue("controller").RawValue;

在语法上无效,所以我预计会出现不同的编译错误(;预期)。

不过,不确定您为什么要尝试在模型中访问 ViewContext。想必,其实是自定义的授权属性吧?

你试过了吗:

var controller = ViewContext.Controller.ValueProvider.GetValue("controller").RawValue;

System.Web.Mvc.ControllerContext controller = ViewContext.Controller.ValueProvider.GetValue("controller").RawValue;

【讨论】:

    【解决方案2】:

    您需要使用传递给 OnAuthorization 函数的 filtercontext。所以你应该可以改变这个:

    var controller = System.Web.Mvc.ControllerContext ViewContext.Controller.ValueProvider.GetValue("controller").RawValue;
    

    到这里:

    var controller = filterContext.Controller.ValueProvider.GetValue("controller").RawValue;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多