我已经创建了一个基本控制器类来覆盖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并设置值。但是,每次到达控制器代码时,我的服务器核心都会爆炸......
答案 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);
}
}