如何通过HttpContextBase获取我的控制器?

时间:2013-02-19 06:53:08

标签: asp.net asp.net-mvc asp.net-mvc-4 controller httpcontext

我有基本控制器,假设它有一个名为AnyProperty的属性:

public class MyBaseController : Controller
    {
        public MyObject AnyProperty { get; set; }

        public MyBaseController()
        {
            AnyProperty = new MyObject();
        }
    }

RoleAttribute我需要使用AnyProperty。我用

public class RoleAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            MyBaseController controllerInstance = new MyBaseController();
            controllerInstance.AnyProperty   // I use like this 
        }
    }

如何通过AnyProperty获取httpContext属性? 不使用MyBaseController实例。有可能吗?

1 个答案:

答案 0 :(得分:2)

这是另一种方法,但它可能会有所帮助:

public override void OnAuthorization(HttpActionContext actionContext)
{
    var controller = actionContext.ControllerContext.Controller as MyBaseController;
    if (controller == null)
    {
        return;
    }
    controller.AnyProperty = new MyObject();
}