Asp.net MVC 3获得当前控制器实例(不仅仅是名称) [英] Asp.net mvc 3- get the current controller instance (not just name)

查看:76
本文介绍了Asp.net MVC 3获得当前控制器实例(不仅仅是名称)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何让当前的控制器名

I know how to get the current controller name

HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString();

但是,有没有什么办法让电流控制器的实例在某些类(而不是在一个动作,而不是在一个视图)?

But is there any way to get the current controller instance in some class (not in an action and not in a view)?

推荐答案

在默认情况下,你只能访问当前的控制器 ControllerContext控制器内.Controller ViewContext.Context 视图中。从某些类,你需要实现一个自定义的访问的ControllerFactory 其中某处存储控制器实例中的请求例如在会话。

By default you can only access the current Controller inside a controller with ControllerContext.Controller or inside a view with ViewContext.Context. To access it from some class you need to implement a custom ControllerFactory which stores the controller instance somewhere in the Request e.g. in the session.

public class MyControllerFactory : DefaultControllerFactory
{
    public override IController CreateController(RequestContext requestContext, string controllerName)
    {
        var controller = base.CreateController(requestContext, controllerName);
        HttpContext.Current.Session["controllerInstance"] = controller;
        return controller;
    }
}

然后在它注册你的的Application_Start

ControllerBuilder.Current.SetControllerFactory(new MyControllerFactory());

和以后可以得到控制器实例:

And you can get the controller instance later:

public class SomeClass
{
    public SomeClass()
    {
        var controller = (IController)HttpContext.Current.Session["controllerInstance"];
    }
}

不过,我会找到一些另一种方式来控制器实例传递给我的课,而不是这个哈克的解决方法。

But I would find some another way to pass the controller instance to my class instead of this "hacky" workaround.

这篇关于Asp.net MVC 3获得当前控制器实例(不仅仅是名称)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆