2011-04-10 56 views
0

空我已經提出,將覆蓋OnActionExecuting如下基控制器類:價值觀重寫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是首先調用並設置值。然而,在達到控制代碼時,我的服務器核心爆炸,每次...

回答

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); 
    } 
} 
+0

該死!時間休息一下。尷尬至少可以說。今晚沒有更多的複製粘貼錯誤。我正在檢查...謝謝。 – Malako 2011-04-10 15:28:03