在重写的OnActionExecuting中设置的值在控制器中为null

时间:2011-04-10 15:19:45

标签: asp.net-mvc-3

我已经创建了一个基本控制器类来覆盖OnActionExecuting,如下所示:

public class BaseController : Controller
{
    public string ActionName;
    public string ControllerName;

    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        ActionDescriptor    actionDescriptor    = filterContext.ActionDescriptor;
        string              ActionName          = actionDescriptor.ActionName;
        string              ControllerName      = actionDescriptor.ControllerDescriptor.ControllerName;
        base.OnActionExecuting(filterContext);
    }
    .
    .
    .

在控制器中我想使用这些值

public class MyController : BaseController
{
    public ActionResult Index(int page)
    {
        if (ActionName == null)
            throw new Exception("ASP.NET MVC3 ABSURDLY GROTESQUE ERROR. CALL FOR REINFORCEMENTS! SERVER CORE ABOUT TO EXPLODE!!!");
            .
            .
            .

首先调用OnActionExecuting并设置值。但是,每次到达控制器代码时,我的服务器核心都会爆炸......

1 个答案:

答案 0 :(得分:4)

不要将string放在OnActionExecuting方法中的那些变量之前,或者您要重新声明新的局部变量,并且您的字段保持为空且未分配:

public class BaseController : Controller
{
    public string ActionName;
    public string ControllerName;

    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var actionDescriptor = filterContext.ActionDescriptor;
        ActionName = actionDescriptor.ActionName;
        ControllerName = actionDescriptor.ControllerDescriptor.ControllerName;
        base.OnActionExecuting(filterContext);
    }
}

为了更好的封装使用属性:

public class BaseController : Controller
{
    public string ActionName { get; private set; };
    public string ControllerName { get; private set; }

    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var actionDescriptor = filterContext.ActionDescriptor;
        ActionName = actionDescriptor.ActionName;
        ControllerName = actionDescriptor.ControllerDescriptor.ControllerName;
        base.OnActionExecuting(filterContext);
    }
}